如何通过Lombok的toString打印UserRel的主键标识符而非完整对象?
自定义UserRel的toString输出格式
当然可以实现这个需求,有两种常用方式:
方式一:用Lombok注解定制输出
利用Lombok的@ToString相关注解,无需完全重写方法就能实现指定格式:
修改后的代码如下:
@Slf4j @ToString(style = ToStringStyle.NO_FIELD_NAMES_STYLE) public class UserRel { @JsonProperty("from") @ToString.Exclude @ToString.Include(expression = "this.from != null ? this.from.getId() : null") private User from; @JsonProperty("rt") private Rtype rtype; @JsonProperty("to") @ToString.Exclude @ToString.Include(expression = "this.to != null ? this.to.getId() : null") private User to; }
说明:
@ToString(style = ToStringStyle.NO_FIELD_NAMES_STYLE)指定生成的toString不显示字段名,只输出值@ToString.Include(expression = ...)自定义要包含的内容,通过表达式获取from.getId()和to.getId(),同时判空避免空指针异常- 原有的
@ToString.Exclude用来排除原始的from和to字段,避免输出整个对象
方式二:手动重写toString方法
如果想要完全自定义格式,直接重写toString方法更灵活:
@Slf4j public class UserRel { @JsonProperty("from") private User from; @JsonProperty("rt") private Rtype rtype; @JsonProperty("to") private User to; @Override public String toString() { String fromId = from != null ? from.getId().toString() : "null"; String rtStr = rtype != null ? rtype.toString() : "null"; String toId = to != null ? to.getId().toString() : "null"; return String.format("UserRel (%s, %s, %s)", fromId, rtStr, toId); } }
这种方式完全脱离Lombok的toString生成逻辑,直接按照你想要的格式拼接字符串,还能灵活处理空值情况。
内容的提问来源于stack exchange,提问作者user352290
相关产品推荐
相关产品推荐

