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.