天天看點

關于toString方法的重寫工具ToStringBuilder

apache的commons-lang3的工具包裡有一個ToStringBuilder類,這樣在打日志的時候可以友善的列印出類執行個體中的各屬性的值。

具體用法如下:

而且支援多種列印格式

多行輸出的:

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。

裡面部分源碼:

需要注意的是:

Builds a <code>toString</code> value using the default <code>ToStringStyle</code> through reflection.

It uses <code>AccessibleObject.setAccessible</code> 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修飾的屬性不能列印出來,但是父類的是可以列印出來的,使用的時候一定要注意了。