How do I use ReflectionToStringBuilder class?

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

Here come 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.SIMPLE_STLYE and we can also output the transient and static attributes 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 ReflectionToString {

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

    public ReflectionToString(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 attributes.
         */
        return ReflectionToStringBuilder.toString(this, 
                ToStringStyle.SIMPLE_STYLE, true, true);
    }

    public static void main(String[] args) {
        ReflectionToString demo = 
                new ReflectionToString(1, "MANU", "Manchester United", "Alex");
        System.out.println("Demo = " + demo);
    }
}

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