我需要获取具有特定注释的字段的值,因此通过反射我能够获取此字段对象。问题是这个字段总是私有(private)的,尽管我事先知道它总是有一个 getter 方法。我知道我可以使用 setAccesible(true) 并获取它的值(当没有 PermissionManager 时),尽管我更喜欢调用它的 getter 方法。
我知道我可以通过查找“get+fieldName”来查找方法(尽管我知道例如 boolean 字段有时被命名为“is+fieldName”)。
我想知道是否有更好的方法来调用这个 getter(许多框架使用 getter/setter 来访问属性,所以也许他们以另一种方式来做)。
谢谢
最佳答案
我认为这应该为您指明正确的方向:
import java.beans.*
for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
System.out.println(pd.getReadMethod().invoke(foo));
}
请注意,您可以自己创建 BeanInfo 或 PropertyDescriptor 实例,即不使用 Introspector。但是,Introspector 会在内部进行一些缓存,这通常是一件好事 (tm)。如果您对没有缓存感到满意,您甚至可以选择
// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);
但是,有很多库可以扩展和简化 java.beans API。 Commons BeanUtils 是一个众所周知的例子。在那里,您只需这样做:
Object value = PropertyUtils.getProperty(person, "name");
BeanUtils 附带了其他方便的东西。即即时值转换(对象到字符串,字符串到对象),以简化用户输入的设置属性。
关于java - 通过反射调用getter的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2638590/