六、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 }
浙公網安備 33010602011771號