六、Lombok 注解详解(4)
8,@Data
(1)@Data 是一个复合注解,用在类上,使用后会生成:默认的无参构造函数、所有属性的 getter、所有非 final 属性的 setter 方法,并重写 toString、equals、hashcode 方法。
1 package com.example.demo; 2 3 import lombok.Data; 4 5 @Data 6 public class User { 7 private String name; 8 private Integer age; 9 }
1 package com.example.demo; 2 3 import lombok.*; 4 5 @Setter 6 @Getter 7 @ToString 8 @EqualsAndHashCode 9 @NoArgsConstructor 10 public class User { 11 private String name; 12 private Integer age; 13 }
9,@Value
@Value 注解和 @Data 类似,区别在于它会把所有成员变量默认定义为 private final 修饰,并且不会生成 set() 方法。
1 // 使用注解 2 @Value 3 public class ValueExample { 4 String name; 5 @Wither(AccessLevel.PACKAGE) @NonFinal int age; 6 double score; 7 protected String[] tags; 8 } 9 10 // 不使用注解 11 public final class ValueExample { 12 private final String name; 13 private int age; 14 private final double score; 15 protected final String[] tags; 16 17 public ValueExample(String name, int age, double score, String[] tags) { 18 this.name = name; 19 this.age = age; 20 this.score = score; 21 this.tags = tags; 22 } 23 24 //下面省略了其它方法 25 //..... 26 }
10,@NonNull
(1)注解在属性上,标识属性是不能为空,为空则抛出异常。换句话说就是进行空值检查。
1 package com.example.demo; 2 3 import lombok.NonNull; 4 5 public class NonNullExample { 6 private String name; 7 8 public NonNullExample(@NonNull User user) { 9 this.name = user.getName(); 10 } 11 }
1 package com.example.demo; 2 3 public class NonNullExample { 4 private String name; 5 6 public NonNullExample(User user) { 7 if (user == null) { 8 throw new NullPointerException("user"); 9 } 10 this.name = user.getName(); 11 } 12 }
1 User user = null; 2 try { 3 NonNullExample example = new NonNullExample(user); 4 }catch (NullPointerException ex) { 5 return ex.toString(); 6 }
11,@Cleanup
(1)用于关闭并释放资源,可以用在 IO 流上;
1 public class CleanupExample { 2 public static void main(String[] args) throws IOException { 3 @Cleanup InputStream in = new FileInputStream(args[0]); 4 @Cleanup OutputStream out = new FileOutputStream(args[1]); 5 byte[] b = new byte[10000]; 6 while (true) { 7 int r = in.read(b); 8 if (r == -1) break; 9 out.write(b, 0, r); 10 } 11 } 12 }
(2)上面相当与如下传统的 Java 代码:
1 public class CleanupExample { 2 public static void main(String[] args) throws IOException { 3 InputStream in = new FileInputStream(args[0]); 4 try { 5 OutputStream out = new FileOutputStream(args[1]); 6 try { 7 byte[] b = new byte[10000]; 8 while (true) { 9 int r = in.read(b); 10 if (r == -1) break; 11 out.write(b, 0, r); 12 } 13 } finally { 14 if (out != null) { 15 out.close(); 16 } 17 } 18 } finally { 19 if (in != null) { 20 in.close(); 21 } 22 } 23 } 24 }