Search code examples
javajava-8guavatostring

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

Solution

  • 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();
    }