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很好的解决了这个问题。让我们一起来看一个例子:

我们的代码经常这样:

 

import java.util.Arrays;

public class ToStringExample {
  private static final int STATIC_VAR = 10;
  private String name;
  private Shape shape = new Square(5, 10);
  private String[] tags;
  private int id;
  
  public String getName() {
    return this.getName();
  }
  
  public static class Square extends Shape {
    private final int width, height;
    
    public Square(int width, int height) {
      this.width = width;
      this.height = height;
    }
    
    @Override public String toString() {
      return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";
    }
  }
  
  @Override public String toString() {
    return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";
  }
}

 

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

 

import lombok.ToString;

@ToString(exclude="id")
public class ToStringExample {
  private static final int STATIC_VAR = 10;
  private String name;
  private Shape shape = new Square(5, 10);
  private String[] tags;
  private int id;
  
  public String getName() {
    return this.getName();
  }
  
  @ToString(callSuper=true, includeFieldNames=true)
  public static class Square extends Shape {
    private final int width, height;
    
    public Square(int width, int height) {
      this.width = width;
      this.height = height;
    }
  }
}

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

 

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

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

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

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

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值