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

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

问题描述

我需要使用特定注释获取字段的值,因此通过反射我能够获取此字段对象.问题是这个字段将永远是私有的,尽管我事先知道它总是有一个 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(许多框架使用 getter/setter 来访问属性,所以也许他们以另一种方式这样做).

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.

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

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