Does it make sense to use reflection when implementing toString()?

tortal picture tortal · May 13, 2013 · Viewed 28.8k times · Source
@Override 
public String toString() { 
    return new Gson().toJson(this);
}

Am I breaking some good practice, "Joshua"-pattern thing, general design pattern or other convention by simply doing this as default behavior for my model objects?

toString() will anyhow only be used in debugging in the paradigm (Android) that we are currently using. That's also the reason why I like seeing the object in JSON since much ORM/json persistence will be happening through http->php/python->mysql and to the local SQLite.

Answer

Amit Kaneria picture Amit Kaneria · Aug 23, 2016

Yes. It's OK to use GSON/Jackson/Reflections library to implement toString() method.

There are few ways to implement toString method.

  1. Reflections (Apache library)

    @Override
    public String toString(){
        return org.apache.commons.lang3.builder.ReflectionToStringBuilder.toString(this);
    }
    
  2. JSON based implementation (GSON, Jackson libraries)

    // GSON library for JSON
    @Override
    public String toString(){
        return new com.google.gson.Gson().toJson(this);
    }
    
    // Jackson libabry for JSON/YAML
    @Override
    public String toString() {
        try {
            return new com.fasterxml.jackson.databind.ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);
        } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
  3. ToStringBuilder (available with apache-commons library)

    @Override
    public String toString() {
        return new org.apache.commons.lang3.builder.ToStringBuilder(this).
            append("field1", field1).
            append("field2", field2).
            toString();
    }
    
  4. Hard-core toString() implementation

    @Override
    public String toString() {
        return new StringBuilder()
            .append("field1:"+field1)
            .append("field2:"+field2)
            .toString();
    }
    
  5. Lombok annotations : Generates toString() at compile time

    import lombok.ToString;
    
    @ToString
    public class ToStringExample {}