import org.apache.commons.lang3.builder.ReflectionToStringBuilder;import org.apache.commons.lang3.builder.ToStringStyle; @Override public String toString() {// return "MsgFarConnectHeader{" +// "srcip='" + srcip + '\'' +// ", srcport=" + srcport +// ", dstip='" + dstip + '\'' +// ", dstport=" + dstport +// "} " + super.toString();
return ReflectionToStringBuilder.toString(this,ToStringStyle.SHORT_PREFIX_STYLE); }
ToStringStyle.SHORT_PREFIX_STYLE 配置打印格式,不显示包名。
打印实例: MsgFarConnectHeader[srcip=2.3.3.3,srcport=0,dstip=3.3.3.3,dstport=0,flag=1557,lenght=18,ver=0,method=5,d=0,t=0,pt=0]
优点:代码简洁 , 属性变化 , 无需修改toString
缺陷:安全性问题 , 反射私有属性值也会暴露,可通过toStringExclude(this,excludeFieldNames)进行排除.