關於toString方法的重寫工具ToStringBuilder


原文:https://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

原理其實就是通過JAVA的reflect(反射)獲取值,然后組成一個Buffer。

里面部分源碼:

 

    /**
     * <p>Append to the <code>toString</code> the start of data indicator.</p>
     * 拼裝結果的
     * @param buffer  the <code>StringBuffer</code> to populate
     * @param object  the <code>Object</code> to build a <code>toString</code> for
     */
    public void appendStart(final StringBuffer buffer, final Object object) {
        if (object != null) {
            appendClassName(buffer, object);
            appendIdentityHashCode(buffer, object);
            appendContentStart(buffer);
            if (fieldSeparatorAtStart) {
                appendFieldSeparator(buffer);
            }
        }
    }
 
    /**
     * <p>Append the {@link System#identityHashCode(java.lang.Object)}.</p>
     * 拼裝對象hashcode
     * @param buffer  the <code>StringBuffer</code> to populate
     * @param object  the <code>Object</code> whose id to output
     */
    protected void appendIdentityHashCode(final StringBuffer buffer, final Object object) {
        if (this.isUseIdentityHashCode() && object!=null) {
            register(object);
            buffer.append('@');
            buffer.append(Integer.toHexString(System.identityHashCode(object)));
        }
    }

 

需要注意的是:

 

Builds a toString value using the default ToStringStyle through reflection.

It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.

Transient members will be not be included, as they are likely derived. Static fields will not be included. Superclass fields will be appended.

也就是說transient和static修飾的屬性不能打印出來,但是父類的是可以打印出來的,使用的時候一定要注意了。

--------------------- 本文來自 vince_zw 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/zhaowen25/article/details/39521899?utm_source=copy 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM