Reputation: 1033
My class has multiple fields with getter and setter
While trying to access the value of a property of a bean i have to check the property name and retrieve the value..
if(property is this )
mybean.getThisProperty()
else if(property is that )
mybean.getThatProperty()
else...
How i can retireve without actually checking for the propertyname ..
BeanUtils.copyProperties
in Spring copies property from one bean to another
Upvotes: 0
Views: 2710
Reputation: 1033
How about the
PropertyUtils.getSimpleProperty
of Apaches commons.beanutils
Upvotes: 2
Reputation: 870
I'm not sure what you are trying to accomplish, but you can do something like that using Reflection:
for (Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
Object value;
try {
if (name.equals(desiredPropertyName)) {
value = field.get(object); // Do whatever you want with the
// value
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
In the above code, we are getting all properties in the "object" eve the private fields without using the getter. This line gives us access to the private fields:
field.setAccessible(true);
This line retrieves the name:
String name = field.getName();
This line retrieves the value:
value = field.get(object);
If you really want to use the getter, then that's another subject, where you will have to use reflection to invoke methods.
Upvotes: 2