Skip to content

FEATURE IDEA: @SuperToString

Maaartinus edited this page Apr 14, 2018 · 2 revisions

Problem

Calling the superclass toString is really ugly; you get: Child[super=Parent[parentField=5], childField=10].

Solution

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].

Maaartin's Notes

  • It's possible to reuse super.toString without internalToString albeit at the price of some copying and creating some garbage. The advantage would be it working even when super.toString isn't lombok-generated. It'd require some more logic to work well (basically, find the parentheses). Just an idea.
  • I'd rename internalToString to appendFieldsTo.
  • I guess, it should 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).
  • The old option callSuper=true is still the right thing in some cases.

Clone this wiki locally