java - 从类名获取类成员

标签 java reflection

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

例如,如果我有

class MyClass {
    Integer a;
    String b;
}

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

最佳答案

如果类已经被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/

相关文章:

C# 委托(delegate)、dll、动态内容

java - String 是关于 switch 的数字类型并且总是编译为 lookupswitch 吗?

java - Spring Boot 页面反序列化 - PageImpl 无构造函数

java:使用ImageIO写入图像文件

java - twitter4j 3.0.5 : sun. security.validator.ValidatorException:PKIX 路径构建失败

java - 在android中点击 Canvas 中的位图图像

java - 有没有办法在java中模拟属性选择器?

c# - PropertyInfo.GetValue() - 如何在 C# 中使用反射索引通用参数?

java - 使用反射在运行时推断 java 泛型参数

c# - 从 .NET 加载 WinRT 程序集