Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to MoreObjects in Java 8

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();
}
like image 781
Costin Avatar asked Sep 21 '15 09:09

Costin


3 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();
}
like image 81
Pavel Uvarov Avatar answered Nov 15 '22 20:11

Pavel Uvarov


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
          +"]";
}
like image 32
Tagir Valeev Avatar answered Nov 15 '22 20:11

Tagir Valeev


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();
}
like image 22
Tunaki Avatar answered Nov 15 '22 22:11

Tunaki