How do I use ReflectionToStringBuilder class?

Implementing toString() method sometimes can become a time consuming process. If you have a class with a few fields it might be alright, but when you deal with a many fields it will surely take some time to update this method every time a new fields come and go.

Here comes the ReflectionToStringBuilder class that can help you to automate the process of implementing the toString() method. This class provides a static toString() method that takes at least a single parameter that refer to an object instance from where the string will be generated.

We can also format the result of the generated string. In the example below we create the to string method with a ToStringStyle.MULTI_LINE_STYLE and we can also output transients and static fields if we want, which by default omitted.

package org.kodejava.example.commons.lang;

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

public class ReflectionToStringDemo {
    private Integer id;
    private String name;
    private String description;
    public static final String KEY = "APP-KEY";
    private transient String secretKey;

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

    @Override
    public String toString() {
        // Generate toString including transient and static fields.
        return ReflectionToStringBuilder.toString(this, 
            ToStringStyle.MULTI_LINE_STYLE, true, true);
    }

    public static void main(String[] args) {
        ReflectionToStringDemo demo = new ReflectionToStringDemo(1, "MANUTD", 
            "Manchester United", "secret**");
        System.out.println("Demo = " + demo);
    }
}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply