Does it make sense to use reflection when implementing toString()?
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)
Yes. It's OK to use GSON/Jackson/Reflections library to implement toString() method.
There are few ways to implement toString method.
Reflections (Apache library)
@Override public String toString(){ return org.apache.commons.lang3.builder.ReflectionToStringBuilder.toString(this); }
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; }
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(); }
Hard-core toString() implementation
@Override public String toString() { return new StringBuilder() .append("field1:"+field1) .append("field2:"+field2) .toString(); }
Lombok annotations : Generates toString() at compile time
import lombok.ToString; @ToString public 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.