I want to get rid of this dependency: import com.google.common.base.MoreObjects;
Is there any simple and/or elegant way to rewrite the following toString()
function using Java 8 native functions?
@Override
public String toString() {
return MoreObjects
.toStringHelper(this)
.add("userId", this.userId)
.add("timestamp", this.timestamp)
.toString();
}
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();
}
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
+"]";
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With