views:

32

answers:

4

I have a bean whose properties I want to access via reflection. I receive the property names in String 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.

+1  A: 

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.

Peter Tillemans
@Peter. Thanks for mentioning `BeanUtils`. I didn't know about it. My next question was going to be if there are libraries that do this. I didn't want to reinvent the wheel. :)
Vivin Paliath
Accepting this answer since it directly answers my original question.
Vivin Paliath
You're welcome and thank you.
Peter Tillemans
A: 

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...

bwawok
+1  A: 

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

Richard Fearn
+1  A: 

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
    }
}
Jon Freedman
Thanks! Just what I was looking for.
Vivin Paliath