好雲推薦官丨飛天加速之星怎樣選擇雲伺服器ECS?
阿新 • • 發佈:2022-03-28
六、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 }(2)上面的 @Data 等效於如下幾個註解結合使用:
1package 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 privatefinal 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 }(2)上面相當與如下 Java 程式碼:
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 }(3)下面是一個簡單的測試樣例:
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 }