栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实体类转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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/683516.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号