在壹些應用程序中,無法事先知道用戶將加載什麽類,而必須用戶指定類名稱以加載類,可以用Class的靜態方法forName()方法實現動態加載類。forClass()我不知道是做什麽的。下面是例子:
import java.lang.reflect.*;
public class ClassDemo
{
public static void main(String[] args)
{
System.out.println("****************getClass()的例子*******************\n");
String name="john";
//獲得name對象的Class實例
Class stringClass=name.getClass();
//下面可以用stringClass實例獲取name對象的相關信息,可以看API文檔,這裏只舉兩個方法
System.out.println("name對象的類型:"+stringClass.getName());
System.out.println("name對象的父類:"+stringClass.getSuperclass().getName());
System.out.println("\n****************forName()的例子*******************\n");
//舉forName()的例子
//動態加載java.util.ArrayList類
//得到類的Class實例後利用Class的方法取得類相關信息
//裏面有好多方法我就不解釋了,妳可以參考API文檔
try
{
Class c=Class.forName("java.util.ArrayList");
int mod=c.getModifiers();
System.out.print(Modifier.toString(mod));
if(Modifier.isInterface(mod))
System.out.print(" interface");
else
System.out.print(" class ");
System.out.println(c.getName()+"{");
System.out.println("\t//********成員變量**********");
Field[] field=c.getDeclaredFields();
for(Field f:field)
{
System.out.print("\t"+Modifier.toString(f.getModifiers()));
System.out.print(" "+f.getType().getName());
System.out.println(" "+f.getName()+";");
}
System.out.println("\t//********構造方法**********");
Constructor[] constructor=c.getDeclaredConstructors();
for(Constructor con:constructor)
{
System.out.print("\t"+Modifier.toString(con.getModifiers()));
System.out.println(" "+con.getName()+"();");
}
System.out.println("\t//*********成員方法*************");
Method[] method=c.getDeclaredMethods();
for(Method mhd:method)
{
System.out.print("\t"+Modifier.toString((mhd.getModifiers())));
System.out.print(" "+mhd.getReturnType().getName());
System.out.println(" "+mhd.getName()+"()");
}
System.out.println("}");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}