Can we find setter method name using property name?
I have a dynamically generated map<propertyName,propertyValue>
By using the key from map (which is propertyName) I need to invoke the appropriate setter method for object and pass the value from map (which is propertyValue).
class A {
String name;
String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
}
My map contain two items:
map<"name","jack">
map<"company","inteld">
Now I am iterating the map and as I proceed with each item from map, based on key (either name or company) I need to call appropriate setter method of class A e.g. for first item I get name as key so need to call new A().setName.
If you use Spring then you'll likely want to use the BeanWrapper
. (If not, you might consider using it.)
Map map = new HashMap();
map.put("name","jack");
map.put("company","inteld");
BeanWrapper wrapper = new BeanWrapperImpl(A.class);
wrapper.setPropertyValues(map);
A instance = wrapper.getWrappedInstance();
This is easier than using reflection directly because Spring will do common type conversions for you. (It will also honor Java property editors so you can register custom type converters for the ones it doesn't handle.)
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