Alternative to MoreObjects in Java 8
Why not build the String yourself? The code is simple to write and to understand, without using any Java 8 specific features.
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append('{')
sb.append("userId=").append(userId);
sb.append(", timestamp=").append(timestamp);
return sb.append('}').toString();
}
I don't see any reason to use this toStringHelper
even prior to Java 8. The plain implementation is not longer:
@Override
public String toString() {
return getClass().getSimpleName()+"["
+"userId: "+this.userId+", "
+"timestamp: "+this.timestamp
+"]";
}
You can use StringJoiner
from java.util
package.
Example:
@Override
public String toString() {
return new StringJoiner(", ", ClassName.class.getSimpleName() + "[", "]")
.add("userId=" + userId)
.add("timestamp=" + timestamp)
.toString();
}
Just featuring a pretty cool solution to let IntelliJ Idea generate the toString with StringJoiner: https://gist.github.com/vlastikcz/6a3b5c158bdb7bf6e9fd (thanks a lot to the author)
Add the code to toString templates: press Alt+Insert, select toString, then select Settings besides Templates, add with the Plus sign: