lombok中的@ToString注解作用

Lombok是一个很好的工具,节省了很多重写方法,而@ToString就是节省了ToString方法,lombok中@ToString就是节省了我们在模型中的冗余代码下面就来举个例子

  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(5, 10);  
  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 
  23.   public String toString() {  
  24.       return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";  
  25.     }  
  26.   }  
  27.     
  28.   @Override 
  29.   public String toString() {  
  30.     return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";  
  31.   }  
  32. }  

引入@ToString注解后的代码

  1.   @ToString(callSuper=true, includeFieldNames=true)  
  2.   public static class Square extends Shape {  
  3.     private final int width, height;  
  4.       
  5.     public Square(int width, int height) {  
  6.       this.width = width;  
  7.       this.height = height;  
  8.     }  
  9.   }  
  10. }  

引自:https://himichaelchu.iteye.com/blog/2124349

猜你喜欢

转载自www.cnblogs.com/dewu123/p/10910582.html