Thursday, July 2, 2009

获取指定CLASS内的信息

import java.lang.reflect.*;

/**
* 获取指定CLASS内的信息(方法,包)
*/

public class ClassInfo {

public ClassInfo() {
}

public static void main(String[] args) throws Exception {
String fullClassName;
if (args.length != 1) {
fullClassName = "java.lang.String";
} else {
fullClassName = args[0];
}

Class cls = Class.forName(fullClassName);

// (1.) 创建实例
Object o = cls.newInstance();

// (2.) 取得package名
Package pack = cls.getPackage();
String packageName = pack.getName();
System.out.println("package: " + packageName);
System.out.println();

// (3.) 取得类名
String className = cls.getName();
System.out.println("class name: " + className);
System.out.println();

// (4.) 取成员变量名
Field[] fields = cls.getFields();
int i;
System.out.println("成员变量");
for (i = 0; i < fields.length; i++) {
System.out.println(" " + fields[i].toString());
}
System.out.println();

// (5.) 取得成员方法
Method[] methods = cls.getMethods();
System.out.println("成员方法");
for (i = 0; i < methods.length; i++) {
System.out.println(" " + methods[i].toString());
}
}
}

No comments: