我有一个类名(作为String
),我想获取所有成员及其类型。我知道我需要使用反射,但是如何使用?
例如,如果我有
class MyClass {
Integer a;
String b;
}
如何获取 a
和 b
的类型和名称?
最佳答案
如果类已经被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
关于java - 从类名获取类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14358910/