Does it make sense to use reflection when implementing toString()?
Solution 1:
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 {}
Solution 2:
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.
Solution 3:
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)
Solution 4:
It's bad for performance because Gson uses introspection to figure out which fields to print.
Apart from that, I think it's ok. That's not the standard Java toString implementation but I don't think changing it would be an anti-pattern.