Use Reflection To build toString method : Class Helper « Apache Common « Java

Use Reflection To build toString method


import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

public class Main {

  private Integer id;

  private String name;

  private String description;

  public static final String KEY = "APP-KEY";

  private transient String secretKey;

  public Main(Integer id, String name, String description, String secretKey) { = id; = name;
    this.description = description;
    this.secretKey = secretKey;

  public String toString() {
    return ReflectionToStringBuilder.toString(this, ToStringStyle.SIMPLE_STYLE, true, true);

  public static void main(String[] args) {
    Main demo = new Main (1, "A", "B", "C");
    System.out.println("Demo = " + demo);


Related examples in the same category

1.Implement hashCode using commons-lang
2.Use CompareToBuilder class to create compareTo method for your own class
3.Implement equals method using commons-lang
4.Jakarta Commons toString Builder