Generic Object toString method using reflections in Java

Here is an example of a generic object toString method using reflections in java. I recently was working on a project where we had to log every transaction to act as an audit. We were working with many objects. We could override the toString method of every object and map every single attribute to every toString method. But instead we took some time in developing a generic solutions. Which saved some time. So I thought, why not share my solution.

Generic Object toString method with reflections

This method will print out every non static attribute of an object. It can even handle attributes of the super type.

package com.memorynotfound;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ObjectUtils {

    public static String toString(Object object, boolean recursive) {
        if (object == null) return "null";

        Class<?> clazz = object.getClass();
        StringBuilder sb = new StringBuilder(clazz.getSimpleName()).append(" {");

        while (clazz != null && !clazz.equals(Object.class)) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field f : fields) {
                if (!Modifier.isStatic(f.getModifiers())) {
                    try {
                        f.setAccessible(true);
                        sb.append(f.getName()).append(" = ").append(f.get(object)).append(",");
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }

            if (!recursive) {
                break;
            }
            clazz = clazz.getSuperclass();
        }

        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.append("}").toString();
    }

}

Generic Object toString Example

Super Class

As an example I will use a simple class to represent the super class.

package com.memorynotfound;

public class Vehicle {

    private String engine = "default";
    private String color = "black";

}

Derived Class

Class Car extends from Vehicle

package com.memorynotfound;

public class Car extends Vehicle {

    private String wheels = "4";
    
}

Testing generic toString method

package com.memorynotfound;

public class Stringify {

    public static void main(String... args){

        // print null
        System.out.println(ObjectUtils.toString(null, false));

        // print vehicle
        Vehicle vehicle = new Vehicle();
        System.out.println(ObjectUtils.toString(vehicle, true));

        // print car
        Car car = new Car();
        System.out.println(ObjectUtils.toString(car, false));
        System.out.println(ObjectUtils.toString(car, true));
    }

}

Output

null
Vehicle {engine = default,color = black}
Car {wheels = 4}
Car {wheels = 4,engine = default,color = black}

References

Download

You may also like...

  • Dev Parker

    Interesting alternative to the commons-lang3 technique; viz
    @Override
    public String toString() {
    return ToStringBuilder.reflectionToString(this);
    }
    ….
    Using commons-lang3 rel 3.3.2
    yields
    [email protected][engine=default,color=black]
    [email protected][wheels=4,engine=default,color=black]