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

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


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)

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

    // GSON library for JSON@Overridepublic String toString(){    return new com.google.gson.Gson().toJson(this);}// Jackson libabry for JSON/YAML@Overridepublic 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)

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

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

    import lombok.ToString;@ToStringpublic class ToStringExample {}


There's no harm in doing it this way. I would suggest you to create a static variable for your Gson instance and enable pretty printing:

static Gson gson = new GsonBuilder().setPrettyPrinting().create();

This way the output from toString method will be formatted.


NOTE: If you use that GSon pretty printing in your toString() method it is going to look like garbage in your debugger because it will be full of newlines.

(Sorry didn't have enough rep to comment above)