0

我有一个类名(作为 a String),我想获取所有成员及其类型。我知道我需要使用反射,但是如何?

例如,如果我有

class MyClass {
    Integer a;
    String b;
}

如何获取 and 的类型和a名称b

4

2 回答 2

2

如果 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
于 2013-01-16T13:01:17.390 回答
1

首先获取类:

Class clazz=ClassforName("NameOfTheClass") 

比询问所有其他信息 Class API

于 2013-01-16T12:56:53.917 回答