从类名获取类的成员

时间:2013-01-16 12:50:28

标签: java reflection

我有一个班级名称(作为String),我希望得到所有成员及其类型。我知道我需要使用反射,但是如何?

例如,如果我有

class MyClass {
    Integer a;
    String b;
}

如何获取ab的类型和名称?

2 个答案:

答案 0 :(得分:1)

首先上课:

Class clazz=ClassforName("NameOfTheClass") 

要求所有其他信息 Class API

答案 1 :(得分:1)

如果类已经被jvm加载,则可以使用Class的静态方法Class.forName(String className);它会返回一个反射对象的句柄。

你会这样做:

//get class reflections object method 1
Class aClassHandle = Class.forName("MyClass");

//get class reflections object method 2(preferred)
Class aClassHandle = MyClass.class;

//get a class reflections object method 3: from an instance of the class
MyClass aClassInstance = new MyClass(...);
Class aClassHandle = aClassInstance.getClass();



//get public class variables from classHandle
Field[] fields = aClassHandle.getFields();

//get all variables of a class whether they are public or not. (may throw security exception)
Field[] fields = aClassHandle.getDeclaredFields();

//get public class methods from classHandle
Method[] methods = aClassHandle.getMethods();

//get all methods of a class whether they are public or not. (may throw security exception)
Method[] methods = aClassHandle.getDeclaredMethods();

//get public class constructors from classHandle
Constructor[] constructors = aClassHandle.getConstructors();

//get all constructors of a class whether they are public or not. (may throw security exception)
Constructor[] constructors = aClassHandle.getDeclaredConstructors();

要从MyClass获取名为b的变量,可以使用。

Class classHandle = Class.forName("MyClass");
Field b = classHandle.getDeclaredField("b");

如果b是整数类型,为了获得它的值,我会这样做。

int bValue = (Integer)b.get(classInstance);//if its an instance variable`

int bValue = (Integer)b.get(null);//if its a static variable