Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an Object instance from a Map

I have a map with keys and string values.
This Map has been built reading a resource bundle where the data is organised in the following way:

height=160
weight=80
name=bob

And I have a class Person which has the fields: height, weight and name.

class Person{
 int height;
 int weight;
 String name;
 //..getter and setter..
}

I would like to create an instance of the class Person from the Map: height:160, weight:80, name:bob The best would be a generic solution, or something that uses some utilities.

Do you have any idea? how can I do that in Java? or using the framework Spring?

like image 212
cloudy_weather Avatar asked Nov 29 '13 16:11

cloudy_weather


1 Answers

Have a look at the Spring BeanWrapper interface and its implementations if you'd like to use something from Spring. You can use it to wrap your bean and dynamically populate your bean from a map like this:

    Map<String, String> properties = new HashMap<>();
    properties.put("height", "160");
    properties.put("weight", "80");
    properties.put("name", "bob");

    BeanWrapper person = new BeanWrapperImpl(new Person());
    for (Map.Entry<String, String> property : properties.entrySet()) {
        person.setPropertyValue(property.getKey(), property.getValue());
    }

    System.out.println(person.getWrappedInstance().toString());

This will print:

    -> Person [height=160, weight=80, name=bob]
like image 122
Kai Sternad Avatar answered Nov 05 '22 21:11

Kai Sternad