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