Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify setter method using property name?

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.

like image 721
Vishal Jagtap Avatar asked Feb 27 '13 14:02

Vishal Jagtap


1 Answers

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.)

like image 92
Alan Krueger Avatar answered Sep 27 '22 22:09

Alan Krueger