MoreObjects alternative in Java 8

I want to get rid of this dependency: import com.google.common.base.MoreObjects;

Is there a simple and / or elegant way to rewrite the following toString() function using native Java 8 functions?

 @Override public String toString() { return MoreObjects .toStringHelper(this) .add("userId", this.userId) .add("timestamp", this.timestamp) .toString(); } 
+6
source share
4 answers

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(); } 
+19
source

Why not build a string yourself? The code is simple to write and understand, without using any specific features of Java 8.

 @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(); } 
+4
source

I see no reason to use this toStringHelper before Java-8. Simple implementation no more:

 @Override public String toString() { return getClass().getSimpleName()+"[" +"userId: "+this.userId+", " +"timestamp: "+this.timestamp +"]"; } 
+4
source

Just showing a pretty cool solution allowing IntelliJ Idea to generate toString with StringJoiner: https://gist.github.com/vlastikcz/6a3b5c158bdb7bf6e9fd (many thanks to the author)
Add code to toString templates: press Alt + Insert, select toString, then select "Settings", except for "Templates", add a plus sign: enter image description here

+1
source

All Articles