Close

How to convert fields of a Java Object to Properties?

[Updated: Feb 6, 2019, Created: Feb 6, 2017]

Java Bean Components Java 

To convert fields/values of an object to key/value pair of java.util.Properties, we can use JavaBean component API. The target object should follow JavaBean conventions.

Following code demonstrates how to do that.

public class BeanUtil {

  public static <T> Properties toProperties (T t) throws Exception {

      Class<T> c = (Class<T>) t.getClass();
      BeanInfo beanInfo = Introspector.getBeanInfo(c);
      Properties p = new Properties();

      for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
          String name = pd.getName();
          Object o = pd.getReadMethod().invoke(t);
          if (o != null)
              p.setProperty(name, o == null ? null : o.toString());
      }
      return p;
  }
}

Let's test above code with an example object:

public class Person {
  private String id;
  private String name;
  private String address;

  public Person (String id, String name, String address) {
      this.id = id;
      this.name = name;
      this.address = address;
  }

  public String getId () {
      return id;
  }

  public void setId (String id) {
      this.id = id;
  }

  public String getName () {
      return name;
  }

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

  public String getAddress () {
      return address;
  }

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

  @Override
  public boolean equals (Object o) {
      if (this == o)
          return true;
      if (o == null || getClass() != o.getClass())
          return false;

      Person person = (Person) o;

      return id != null ? id.equals(person.id) : person.id == null;
  }

  @Override
  public int hashCode () {
      return id != null ? id.hashCode() : 0;
  }
}
public class Main {

  public static void main (String[] args) throws Exception {
      Person p = new Person("1", "Julia", "Coverdale dr, Dallas");
      Properties properties = BeanUtil.toProperties(p);
      System.out.println(properties);
  }
}

Output

{address=Coverdale dr, Dallas, name=Julia, class=class com.logicbig.example.Person, id=1}

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.3.9

convert-fields-to-properties Select All Download
  • convert-fields-to-properties
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • BeanUtil.java

    See Also