Lombok 之 ToString

LomBok 的相关目录已经整理出来,希望大家可以根据需求自助学习,好工具要大家分享:

@Cleanup     

@Getter, @Setter

@ToString

@EqualsAndHashCode

@Constructor

@Data & @Value

@SneakyThrows

@Synchronized

@Getter(lazy=true)

@Log

 

很多时候我们进行一些探索和功能验证的时候,需要用到当前对象的toString方法,尤其是在进行xml解析,json解析这样的功能验证的时候,之前工作中就遇到过需要解析xml 和json,如果每次验证都启动tomcat的话会非常的消耗时间,所以索性直接Override toString方法,然后测试功能。

对于重写toString方法这件事大多数的做法都是把变量按照顺序,用提示语句区分,逐个打印出来,不知道屏幕前的小伙伴有多少为了这样事情苦恼的。因为写这样的代码实在头疼,又要关注拼接字符串的格式。在Lombok中,一个@ToString annotation很好的解决了这个问题。让我们一起来看一个例子:

我们的代码经常这样:

 

Java代码   收藏代码
  1. import java.util.Arrays;  
  2.   
  3. public class ToStringExample {  
  4.   private static final int STATIC_VAR = 10;  
  5.   private String name;  
  6.   private Shape shape = new Square(510);  
  7.   private String[] tags;  
  8.   private int id;  
  9.     
  10.   public String getName() {  
  11.     return this.getName();  
  12.   }  
  13.     
  14.   public static class Square extends Shape {  
  15.     private final int width, height;  
  16.       
  17.     public Square(int width, int height) {  
  18.       this.width = width;  
  19.       this.height = height;  
  20.     }  
  21.       
  22.     @Override public String toString() {  
  23.       return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";  
  24.     }  
  25.   }  
  26.     
  27.   @Override public String toString() {  
  28.     return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";  
  29.   }  
  30. }  

 

其实,我们的代码可以这样:

 

Java代码   收藏代码
  1. import lombok.ToString;  
  2.   
  3. @ToString(exclude="id")  
  4. public class ToStringExample {  
  5.   private static final int STATIC_VAR = 10;  
  6.   private String name;  
  7.   private Shape shape = new Square(510);  
  8.   private String[] tags;  
  9.   private int id;  
  10.     
  11.   public String getName() {  
  12.     return this.getName();  
  13.   }  
  14.     
  15.   @ToString(callSuper=true, includeFieldNames=true)  
  16.   public static class Square extends Shape {  
  17.     private final int width, height;  
  18.       
  19.     public Square(int width, int height) {  
  20.       this.width = width;  
  21.       this.height = height;  
  22.     }  
  23.   }  
  24. }  

 这样的方便方式节省了好多拼接字符串的功夫。

 

lombok.toString.includeFieldNames = [true | false] (default: true)

是否包含field的信息,如果值为true ,则可以在toString方法中给出field 的name。

lombok.toString.doNotUseGetters = [true | false] (default: false)

如果值为true,则Lombok会直接获取field 而不是通过get方法获取值。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值