StringBuilder vs String concatenation in toString() in Java

后端 未结 18 2190
北恋
北恋 2020-11-21 04:18

Given the 2 toString() implementations below, which one is preferred:

public String toString(){
    return \"{a:\"+ a + \", b:\" + b + \", c: \"         


        
18条回答
  •  不知归路
    2020-11-21 05:02

    Apache Commons-Lang has a ToStringBuilder class which is super easy to use. It does a nice job of both handling the append-logic as well as formatting of how you want your toString to look.

    public void toString() {
         ToStringBuilder tsb =  new ToStringBuilder(this);
         tsb.append("a", a);
         tsb.append("b", b)
         return tsb.toString();
    }
    

    Will return output that looks like com.blah.YourClass@abc1321f[a=whatever, b=foo].

    Or in a more condensed form using chaining:

    public void toString() {
         return new ToStringBuilder(this).append("a", a).append("b", b").toString();
    }
    

    Or if you want to use reflection to include every field of the class:

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

    You can also customize the style of the ToString if you want.

提交回复
热议问题