Java Language Apache Commons Lang Implement toString() method


Example

To implement the toString method of an object easily you could use the ToStringBuilder class.

Selecting the fields:

@Override
public String toString() {

    ToStringBuilder builder = new ToStringBuilder(this);
    builder.append(field1);
    builder.append(field2);
    builder.append(field3);
    
    return builder.toString();
}

Example result:

ar.com.jonat.lang.MyClass@dd7123[<null>,0,false]

Explicitly giving names to the fields:

@Override
public String toString() {

    ToStringBuilder builder = new ToStringBuilder(this);
    builder.append("field1",field1);
    builder.append("field2",field2);
    builder.append("field3",field3);
    
    return builder.toString();
}

Example result:

ar.com.jonat.lang.MyClass@dd7404[field1=<null>,field2=0,field3=false]

You could change the style via parameter:

@Override
public String toString() {

    ToStringBuilder builder = new ToStringBuilder(this,
            ToStringStyle.MULTI_LINE_STYLE);
    builder.append("field1", field1);
    builder.append("field2", field2);
    builder.append("field3", field3);

    return builder.toString();
}

Example result:

ar.com.bna.lang.MyClass@ebbf5c[
  field1=<null>
  field2=0
  field3=false
]

There are some styles, for example JSON, no Classname, short, etc ...

Via reflection:

@Override
public String toString() {
    return ToStringBuilder.reflectionToString(this);
}

You could also indicate the style:

@Override
public String toString() {
    return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}