GetDeclaredField (String) vs getMethod (String) for private fields in bean

I have a bean whose properties I want to get through reflection. I get property names in string form. beans have getter methods for their private fields.

I am currently getting a field using getDeclaredField(fieldName) , making it available with setAccessible(true) , and then retrieving its value with get .

Another way to do this is to use the name of the field and add get to it, then get the method with that name from the class and finally call the method to get the value of the private field.

Which way is better?

EDIT

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

+4
source share
4 answers

It depends on your use, but in general, I would prefer to use a getter, as this is a β€œnormal” way, and in most cases it will do what the class developer expects.

In principle, if the class developer has made the field private, he can freely do what he likes, for example, delete it later, if it can be calculated differently. Then access to the field will break, I hope, right away, if you are not lucky after 3 months, when no one else remembers.

Please note that there are libraries there, such as apache commons BeanUtils (I believe there is one from Spring) that does this for you and offers a more reasonable interface, such as a hash map.

+1
source

Perhaps the getter method is used, since it may have additional behavior, except to return the value of the property. However, it depends on the class.

+1
source

You can take a look at the Introspector class, this is a good wrapper if you want to deal only with the properties that you can get the 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 } } 
+1
source

Better how?

You can write 20 lines of unit test to find out which is faster. You could write both and look at them to see which is easier to read. If one method is easier to read and faster, go to it. If not, you will have to pick up your poison ...

0
source

All Articles