开发者

getDeclaredField(String) vs. getMethod(String) for private fields in a bean

I have a bean whose properties I want to access via reflection. I receive the property names in 开发者_如何学GoString form. The beans have getter methods for their private fields.

I am currently getting the field using getDeclaredField(fieldName), making it accessible by using setAccessible(true) and then retrieving its value using get.

Another way to go about it would be to capitalize the field name and add get to the front of it, and then get the method by that name from the class and finally invoke the method to get the value of the private field.

Which way is better?

EDIT

Perhaps I should explain what I mean by "better"... By "better", I mean in the sense of best-practices. Or, if there are any subtle caveats or differences.


You may want to take a look at the Introspector class, its a nice wrapper if you want to only deal with properties which have been exposed, you can get a BeanInfo object and then call getPropertyDescriptors(), for example:

final BeanInfo info = Introspector.getBeanInfo(clazz);
for (PropertyDescriptor prop : info.getPropertyDescriptors()) {
    final Method read = prop.getReadMethod();
    if (read != null) {
        // do something
    }
}


It depends of your use, but in general I would prefer to use the getter as this is the "normal" way and will in more cases do the thing the developer of the class expects gets done.

In principle, if the developer of the class has made the field private he is free to do as he pleases, like for instance removing it later if it can be calculated in another way. Then the fieldaccess will break, hopefully immediately, if you are unlucky 3 months later when nobody remembers anymore.

Note that there a libraries like apache commons BeanUtils (I believe there is one in Spring too) which does that for you and offer a more sane interface, like a hash map for example.


Possibly using the getter method, as it may have additional behaviour besides just returning the property's value. However this depends on the class.


Better in what way?

You could write a 20 line unit test to see which is faster. You could write both and look at them to see which is easier to read. If one way is both easier to read and faster, go for it. If not, you will have to pick your poison...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜