當前位置:編程學習大全網 - 源碼下載 - 關於forClass,getClass,forName方法

關於forClass,getClass,forName方法

壹個java.lang.Class對象代表了Java應用程序在運行時所加載的類或接口實例,也就是說被加載的類在JVM中以Class的實例存在,Class對象由JVM自動產生。通過Object的getClass()方法來獲取每壹個對象對應的Class對象,或的Class對象之後可以用Class對象上的方法取得類的信息。

在壹些應用程序中,無法事先知道用戶將加載什麽類,而必須用戶指定類名稱以加載類,可以用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();

}

}

}

  • 上一篇:如何開發軟件以滿足對軟件日益增長的需求
  • 下一篇:妳的v助手源代碼
  • copyright 2024編程學習大全網