Deep dive in to BeanUtilsBean .populate

Suraj Batuwana
2 min readMay 7, 2021

BeanUtilsBean.populate, is written to populate the JavaBeans properties of the specified bean, based on the specified name/value pairs.

Lets start with an example, a map with 2 keys name and address, and need to populate to Person object

Map<String, Object> map = new HashMap<>();
map.put("name", "Samuel")
map.put("address", " 12333 Hay ...... QLD 4743")
@Data
public class Person {
private String name;
private String address
}//Simple use of BeanUtilsBean is
Person person = new Person();
BeanUtilsBean.populate(person, map);

if you check the person object after populate, it will have new values.

What is Keys and different

Map<String, Object> map = new HashMap<>();
map.put("personName", "Samuel")
map.put("personAddress", " 12333 Hay ...... QLD 4743")

This will return empty object even after populate as map keys and class variables are not same.

There might be several solutions for this but esiest one is create a another map from previous map with correct keys like

Map<String, Object> newMap = new HashMap<>();
map.forEach((k, v) -> {
if(x.equals("personName")) {
newMap.put("name", v);
}else if(x.equals("personAddress")) {
newMap.put("address", v);
}
}
);

now you can use same technique to populate the new map, then it should work.

Now lets do some few more changes

@Data
public class Person {
private String name;
private String address
private LocalDate dateOfBirth;
private SEX sex;
}public enum Sex {
MALE("Male"),

FEMALE("Female")
...
}

How can you do the population now

Date Converter

class MyDateConverter implements Converter {

@Override
public Object convert(Class Date, Object value) {

if(value!=null) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("soem date pattern string");
ZonedDateTime zonedDateTime = ZonedDateTime.parse(value.toString(), dtf);
return zonedDateTime.toLocalDate();
}
}
}
And register as BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance();
beanUtilsBean.getConvertUtils().register(new MyDateConverter(), LocalDate.class);

Similar to that you can write converter for ENUM

If you like this page please Buy me a Coffee — https://www.buymeacoffee.com/shareknowlage

--

--

Suraj Batuwana

Technology Evangelist, Technical Blogger with multidisciplinary skills with experience in full spectrum of design, architecture and development