JavaExample.net | Serialize a java bean into string with ReflectionToStringBuilder

If we need a simple utility to log bean values transforming them into a string rapresentation we can use ReflectionToStringBuilder

To use this class we need common.lang jar library.

Example:

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
 
public class MyBean
{
 
    private String firstValue;
    private int secondValue;
 
//... setter and getter
 
public static main(String[] args)
{
      MyBean myBean = new MyBean();
      myBean.setFirstValue("Hello");
      myBean.setSecondValue(1);
      System.out.println(ReflectionToStringBuilder.toString(this));
}
 
 
}

When use it:

  • logging stack value of a bean in case of exception
  • logging stack input value arriving from bean request
  • etc
Share →

Leave a Reply

Your email address will not be published. Required fields are marked *