ToStringBuilder类

文章来源:http://blog.csdn.net/zhaowen25/article/details/39521899

apache的commons-lang3的工具包里有一个ToStringBuilder类,这样在打日志的时候可以方便的打印出类实例中的各属性的值。

具体用法如下:

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class Message {

    private String from;

    private String to;

    private String body;

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }
    
    public static void main(String[] args) {
        Message msg = new Message();
        msg.setFrom("vince");
        msg.setTo("mike");
        msg.setBody("hello");
        System.out.println(msg.toString());
    }
}

而且支持多种打印格式

多行输出的:

com.vince.im.dto.Message@af72d8[
  from=vince
  to=mike
  body=hello
]

默认一行的:

com.vince.im.dto.Message@af72d8[from=vince,to=mike,body=hello]

 

NO_FIELD_NAMES_STYLE:

com.vince.im.dto.Message@af72d8[vince,mike,hello]

 

SHORT_PREFIX_STYLE:

Message[from=vince,to=mike,body=hello]

 

SIMPLE_STYLE:

vince,mike,hello

posted @ 2018-03-16 00:01  kangjie  阅读(1452)  评论(0编辑  收藏  举报