java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.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) { = id; = name;
        this.description = description;
        this.secretKey = secretKey;

    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);