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

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

实体类转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=,updateBy=RegisterInit,updateDate=]
//ToStringStyle.SHORT_PREFIX_STYLE
BosbaseObject[createBy=RegisterInit,createDate=,updateBy=RegisterInit,updateDate=]
//ToStringStyle.SIMPLE_STYLE
RegisterInit,,RegisterInit,
//ToStringStyle.MULTI_LINE_STYLE
com.phfund.aplus.ajds.db.common.persistence.model.BosbaseObject@62ddbd7e[
  createBy=RegisterInit
  createDate=
  updateBy=RegisterInit
  updateDate=
]
//ToStringStyle.NO_FIELD_NAMES_STYLE
com.phfund.aplus.ajds.db.common.persistence.model.BosbaseObject@62ddbd7e[RegisterInit,,RegisterInit,]

五、使用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=]

六、使用lombok中的ToString注解

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5684074.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存