Close

How to convert java.util.Map To Java Bean?

[Last Updated: Apr 28, 2020]

Java Bean Components Java 

Following example shows how to populate a Java Bean fields from java.util.Map.

Example

package com.logicbig.example;

public class Person {
  private String name;
  private int age;
  private String address;

  public String getName() {
      return name;
  }

  public void setName(String name) {
      this.name = name;
  }

  public int getAge() {
      return age;
  }

  public void setAge(int age) {
      this.age = age;
  }

  public String getAddress() {
      return address;
  }

  public void setAddress(String address) {
      this.address = address;
  }

  @Override
  public String toString() {
      return "Person{" +
              "name='" + name + '\'' +
              ", age=" + age +
              ", address='" + address + '\'' +
              '}';
  }
}
package com.logicbig.example;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class MapToBeanUtil {

  public static void main(String[] args) {
      Map<String, Object> map = new HashMap<>();
      map.put("name", "Tina");
      map.put("age", 30);
      map.put("address", "101 Sun Street, Yellow Town");
      Person person = toBean(map, Person.class);
      System.out.println(person);
  }

  public static <T> T toBean(Map<String, Object> beanPropMap, Class<T> type) {
      try {
          T beanInstance = type.getConstructor().newInstance();
          for (Object k : beanPropMap.keySet()) {
              String key = (String) k;
              Object value = beanPropMap.get(k);
              if (value != null) {
                  try {
                      Field field = type.getDeclaredField(key);
                      field.setAccessible(true);
                      field.set(beanInstance, value);
                      field.setAccessible(false);
                  } catch (Exception e) {
                      e.printStackTrace();

                  }
              }
          }
          return beanInstance;
      } catch (Exception e) {
          e.printStackTrace();
      }
      return null;
  }
}
Person{name='Tina', age=30, address='101 Sun Street, Yellow Town'}

See Also