通过反射调用吸气剂的最佳方式 [英] Best way of invoking getter by reflection

查看:70
本文介绍了通过反射调用吸气剂的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取具有特定注释的字段的值,因此使用反射我可以获得此字段对象。问题是这个字段将永远是私有的,虽然我事先知道它总是有一个getter方法。我知道我可以使用setAccesible(true)并获取它的值(当没有PermissionManager时),虽然我更喜欢调用它的getter方法。

I need to get the value of a field with a specific annotation, So with reflection I am able to get this Field Object. The problem is that this field will be always private though I know in advance it will always have a getter method. I know that I can use setAccesible(true) and get its value (when there is no PermissionManager), though I prefer to invoke its getter method.

我知道我可以通过查找get + fieldName寻找方法(虽然我知道例如布尔字段有时被命名为is + fieldName)。

I know that I could look for the method by looking for "get+fieldName" (though I know for example for boolean fields are sometimes named as "is+fieldName").

我想知道如果有更好的方法来调用这个getter(许多框架使用getters / setters来访问属性,所以也许他们以另一种方式执行)。

I wonder if there is a better way to invoke this getter (many frameworks use getters/setters to access the attributes so maybe they do in another way).

谢谢

推荐答案

我认为这应该指向正确的方向:

I think this should point you towards the right direction:

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)。如果您在没有缓存的情况下感到满意,您甚至可以选择

Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for

// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);

但是,有很多库可以扩展和简化java.beans API。 Commons BeanUtils是一个众所周知的例子。在那里,你只需:

However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:

Object value = PropertyUtils.getProperty(person, "name");

BeanUtils附带其他方便的东西。即,即时值转换(对象到字符串,字符串到对象),以简化用户输入的设置属性。

BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.

这篇关于通过反射调用吸气剂的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆