Lombok 之 ToString

源:http://himichaelchu.iteye.com/blog/2124349
评:
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代码  收藏代码
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) + ")"; 
  } 



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



Java代码  收藏代码
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方法获取值。

猜你喜欢

转载自mauersu.iteye.com/blog/2414053
今日推荐