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?
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]
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