Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 403
Vivin Paliath Avatar asked Oct 14 '22 00:10

Vivin Paliath


1 Answers

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
    }
}
like image 139
Jon Freedman Avatar answered Oct 16 '22 14:10

Jon Freedman