实体类转String(即重写toString方法)的N种方式

 类如下:

public class BosBaseObject implements Serializable {
    private String createBy;
    private Long createDate;
    private String updateBy;
    private Long updateDate;
}

一、直接使用(不重写)

打印的数据只有类的hashCode,并没有将类中的数据打印出来

BosBaseObject baseObject = new BosBaseObject();
baseObject.setCreateBy("RegisterInit");
baseObject.setUpdateBy("RegisterInit");
System.out.println(baseObject);
log.info("数据为:{}", baseObject);
com.****.model.BosBaseObject@62ddbd7e
[2021-12-28 13:40:59.606][INFO ][biz_seq:][com.****.controller.OneController-77][数据为:com.****.model.BosBaseObject@62ddbd7e]

因为没有重写toString()方法,直接继承了Object类的toString()方法如下:

public String toString() {
	return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

二、手动拼接数据

@Override
public String toString() {
	return "BosBaseObject{" +
			"createBy='" + createBy + '\'' +
			", createDate=" + createDate +
			", updateBy='" + updateBy + '\'' +
			", updateDate=" + updateDate +
			'}';
}
BosBaseObject{createBy='RegisterInit', createDate=null, updateBy='RegisterInit', updateDate=null}

 三、使用JSONObject

@Override
public String toString() {
	return JSONObject.toJSONString(this);
}
{"createBy":"RegisterInit","updateBy":"RegisterInit"}

 四、使用ToStringBuilder

String str = ReflectionToStringBuilder.toString(baseObject, ToStringStyle.SHORT_PREFIX_STYLE);

不同的Style打印的格式不一样,如下

//ToStringStyle.DEFAULT_STYLE
com.phfund.aplus.ajds.db.common.persistence.model.BosBaseObject@62ddbd7e[createBy=RegisterInit,createDate=<null>,updateBy=RegisterInit,updateDate=<null>]
//ToStringStyle.SHORT_PREFIX_STYLE
BosBaseObject[createBy=RegisterInit,createDate=<null>,updateBy=RegisterInit,updateDate=<null>]
//ToStringStyle.SIMPLE_STYLE
RegisterInit,<null>,RegisterInit,<null>
//ToStringStyle.MULTI_LINE_STYLE
com.phfund.aplus.ajds.db.common.persistence.model.BosBaseObject@62ddbd7e[
  createBy=RegisterInit
  createDate=<null>
  updateBy=RegisterInit
  updateDate=<null>
]
//ToStringStyle.NO_FIELD_NAMES_STYLE
com.phfund.aplus.ajds.db.common.persistence.model.BosBaseObject@62ddbd7e[RegisterInit,<null>,RegisterInit,<null>]

五、使用ReflectionToStringBuilder,效果同上

String str = ReflectionToStringBuilder.toString(baseObject,ToStringStyle.SHORT_PREFIX_STYLE);

使用setExcludeFieldNames实现指定某些字段不输出(比如隐藏password)

String str = new ReflectionToStringBuilder(this,ToStringStyle.SHORT_PREFIX_STYLE).setExcludeFieldNames(new String[]{"createBy","createDate"}).toString();
BosBaseObject[updateBy=RegisterInit,updateDate=<null>]

六、使用lombok中的ToString注解

具体参看https://blog.csdn.net/WZH577/article/details/100164550


版权声明:本文为WZH577原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。