java - 反射器: How to list getters of a class and invoke them in Java?

标签 java reflection

下面的 SO 文章很好地展示了如何使用内省(introspection)器列出与类关联的 getter。

Java Reflection: How can i get the all getter methods of a java class and invoke them

我在这篇文章中使用的代码是:

for(PropertyDescriptor propertyDescriptor : 
  Introspector.getBeanInfo(User.class,Object.class).getPropertyDescriptors()){
  System.out.println(propertyDescriptor.getReadMethod());          
}

这对于我的“User”类效果很好,输出为:

public java.lang.String com.SingleEntity.mind_map.User.getName()
public int com.SingleEntity.mind_map.User.getNumber_of_entries()
public java.lang.String com.SingleEntity.mind_map.User.getUser_created_date()

我现在的问题是,我现在如何调用这些方法?如果在链接中以某种方式解释了这一点,我深表歉意,但我不明白它,并且非常感谢一个例子。

当然,我知道如何正常调用类方法,但这里的假设是,在上面的代码发现 getter 之前,程序不知道它们。

最佳答案

PropertyDescriptor.getReadMethod() 返回一个 Method 对象。

只需使用Method.invoke(Object instance, Object...args)

有些东西......

for(PropertyDescriptor propertyDescriptor : 
Introspector.getBeanInfo(User.class,Object.class).getPropertyDescriptors()){
    try {
        Object value = propertyDescriptor
                       .getReadMethod()

               .invoke(myUserInstance, (Object[])null);      
    }
    catch (IllegalAccessException iae) {
        // TODO
    }
    catch (IllegalArgumentException iaee) {
        // TODO
    }
    catch (InvocationTargetException ite) {
        // TODO
    }
}

关于java - 反射器: How to list getters of a class and invoke them in Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26911944/

相关文章:

java - 为什么 String 是 Java 中唯一存在文字的类?

java - Java jar 文件的 list 中定义的类路径的范围是什么

java - exoplayer 不玩添加并崩溃了

java - 如何在 Java 中将字符串转换为 Time 对象?

用于创建新对象的 Java 反射

java - 无法让Java和C#通过socket进行通信

java - getConstructor() 返回一个未实现的构造函数

java - 如何在 java 中使用 java.lang.reflect 包将值分配给 varialable

Golang 使用反射一个一个地改变一个结构的字段

powershell - 构造一个自定义对象,其属性将按定义顺序枚举