java反射(收集)

May 3, 2007

Class创建:

1 String name = “caterpillar”;
Class stringClass = name.getClass();

2 Class stringClass = String.class;

3 Class c = Class.forName(args[0]);

Class物件的訊息是在編譯時期就被加入至.class檔案中,它是Java支援執行時期型別辨識(RTTI,Run- Time Type Information或Run-Time Type Identification)的一種方式,在編譯時期編譯器會先檢查對應的.class檔案,而執行時期JVM在沒有用到該類別時,就不會載入它,如果要用到時,JVM會先檢查對應的Class物件是否已經載入,如果沒有載入,則會尋找對應的.class檔案並載入它。

您可以使用Class.forName()方法動態加載類別,之後使用Class的newInstance()方法產生實例

从Class中获取信息
Class c = Class.forName(args[0]);
Package p = c.getPackage();
System.out.println(p.getName());
int m = c.getModifiers();
System.out.print(Modifier.toString(m) + ” “);
if(Modifier.isInterface(m)) { System.out.print(”interface “); }
else { System.out.print(”class “); }
System.out.println(c.getName() + ” {”);
Field[] fields = c.getDeclaredFields();
for(Field field : fields) {
System.out.print(”\t” + Modifier.toString(field.getModifiers()));
System.out.print(” ” + field.getType().getName() + ” “);
System.out.println(field.getName() + “;”);
}

Comments »

The URI to TrackBack this entry is: http://lwj.blogsome.com/2007/05/03/p34/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.