How have RecursiveToStringStyle and JSON_STYLE using commons-lang3

I found the solution. I need to Override the method toString of each classes (X and Y in this case)

public Class X {

  private String a;
  private String b;
  private Y y;

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

public Class Y {
  private String c;
  private String d;

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

And now, with the approach 1 It's working.


You can extend the RecursiveToStringStyle class to write your own style class and set the parameters to match the JSON_STYLE or any other style for that matter.

class CustomStyle extends RecursiveToStringStyle {

    public CustomStyle() {
        super();
        super.setUseClassName(false);
        super.setUseIdentityHashCode(false);
        super.setContentStart("{");
        super.setContentEnd("}");
        super.setArrayStart("[");
        super.setArrayEnd("]");
        super.setFieldSeparator(",");
        super.setFieldNameValueSeparator(":");
        super.setNullText("null");
        super.setSummaryObjectStartText("\"<");
        super.setSummaryObjectEndText(">\"");
        super.setSizeStartText("\"<size=");
        super.setSizeEndText(">\"");
    }
}

public class Z {
    public String objectToString(Object obj) {
        ToStringStyle style = new CustomStyle();
        return new ReflectionToStringBuilder(obj, style).toString();
    }
}

To create a custom style, a good point will be to look at the style parameters set in the ToStringStyle class. You can use the setter methods to customize the default settings in your custom implementation.