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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With