-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
FEATURE IDEA: @SuperToString
Emile de Weerd edited this page Apr 17, 2018
·
3 revisions
Calling the superclass toString is really ugly; you get: Child[super=Parent[parentField=5], childField=10].
To generate 'super-capable toString', generate the following code for any class marked @SuperToString
with no 'extends', or with 'extends X' where X is typelibrary-resolvable to java.lang.Object
, or with @SuperToString(callSuper = false)
:
@Override public String toString() {
StringBuilder out = new StringBuilder("MyTypeName[");
internalToString(out, ", ");
if (out.length() > 11) out.setLength(out.length() - 2);
return out.append("]").toString();
}
protected void internalToString(StringBuilder out, String sep) {
out.append("fieldName=").append(fieldName).append(sep);
// actually, do what toString usually does, so, use Arrays.toString if it's an array, etc.
}
and for classes which extend something, the same, except internalToString
looks like:
@Override protected void internalToString(StringBuilder out, String sep) {
super.internalToString(out, sep);
out.append("fieldName=").append(fieldName).append(sep);
}
Now you get a much nicer toString: Child[parentField=5, childField=10]
.
- It should probably be an option on
@ToString
rather then a new annotation, as the two can't be combined (especially,@SuperToString
with the old@ToString
on the superclass would not work when a helper method gets used). Maybe@ToString(embedSuper=true)
? - Rename
internalToString
toappendFieldsTo
? - It's possible to reuse
super.toString
withoutinternalToString
albeit at the price of some copying and creating some garbage. The advantage would be it working even whensuper.toString
isn't lombok-generated. It'd require some more logic to work well (basically, find the parentheses). - When this gets implemented, then all lombok-generated
toString
methods should use the helper method, so that they can be used in subclasses (an exception can be made for final classes). - Like equalsAndHashCode it would be good to propose the embedSuper tag property also as a lombok.config property so the behavior is activated for a whole project.