目录
@NoArgsConstructor/@RequiredArgsConstructor/@AllArgsConstructor
lombok简介
lombok是一个java类库,能够自动植入开发者的编译器来辅助java开发。使用lombok,可以使用一个注解来代替getter等方法的编写。使用起来非常简单,maven pom.xml文件中加入如下依赖,
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency>
在实体类上加上注解@Data
@Data public class Employee{ private Long id; private String name; private String department; private Long number; }
测试代码如下:
从图片中可以看出有编译错误代码,但是执行这个测试用例可以成功。
IDEA配置lombok
IDEA中安装lombok插件可以去除编译错误,跟安装普通插件一样,File->Settings->Plugins,如下图
重启后编译错误消失,注意点击图中右下角的Enable按钮
lombok常用的注解
@Getter/@Setter
注解在类上,为所有非静态变量生产get和set方法
@ToString
注解在pojo类上面,为类生成toString方法,如果要在toString中排除一个变量,可以在该变量上面加上注解ToString.exclude,如果要在toString中打印出非静态变量,在非静态变量上增加@ToString.Include,如果要改变打印出的变量名称,在变量上加注解@ToString.Include(name = "username"),也可以通过@ToString.Include(rank = -1)来配置打印顺序,rank值越大越先打印 ·
如下示例:
@Setter @ToString public class ToStringExample { private static final int STATIC_VAR = 10; /**姓名**/ private String name; private Square square = new Square(5, 10); private String[] tags; @ToString.Include(rank = 1) private static String password = "123456"; @ToString.Exclude private int id; public String getName() { return this.name; } @ToString(callSuper=true) public static class Square { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; } } public static void main(String[] args){ ToStringExample toStringExample = new ToStringExample(); toStringExample.setName("jinjunzhu"); toStringExample.setTags(new String[]{"123", "234"}); System.out.println(toStringExample.toString()); } }
打印结果如下:
ToStringExample(password=123456, name=jinjunzhu, square=ToStringExample.Square(super=boot.lombok.ToStringExample$Square@446cdf90, width=5, height=10), tags=[123, 234])
@NonNull
检查借据是否为空,如果为空,抛出空指针异常
如下代码:
public class NonNullExample { private String name; public NonNullExample(@NonNull String name) { this.name = name; } public static void main(String[] args){ NonNullExample nonNullExample = new NonNullExample(null); } }
执行后结果如下:
Exception in thread "main" java.lang.NullPointerException: name is marked non-null but is null at boot.lombok.NonNullExample.<init>(NonNullExample.java:10) at boot.lombok.NonNullExample.main(NonNullExample.java:15)
@EqualsAndHashCode
为类生成equals(Object other)和hashcode()方法,默认为non-static, non-transient生成,也可以用@EqualsAndHashCode.Include或@EqualsAndHashCode.Exclude来生成或不生成
如下2段代码等价
@EqualsAndHashCode public class EqualsAndHashCodeExample { private transient int transientVar = 10; private String name; private double score; @EqualsAndHashCode.Exclude private Square shape = new Square(5, 10); private String[] tags; @EqualsAndHashCode.Exclude private int id; public String getName() { return this.name; } @EqualsAndHashCode() public static class Square { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; } } }
这段代码等价于如下代码
public class EqualsAndHashCodeExample { private transient int transientVar = 10; private String name; private double score; private Shape shape = new Square(5, 10); private String[] tags; private int id; public String getName() { return this.name; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeExample)) return false; EqualsAndHashCodeExample other = (EqualsAndHashCodeExample) o; if (!other.canEqual((Object)this)) return false; if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false; if (Double.compare(this.score, other.score) != 0) return false; if (!Arrays.deepEquals(this.tags, other.tags)) return false; return true; } @Override public int hashCode() { final int PRIME = 59; int result = 1; final long temp1 = Double.doubleToLongBits(this.score); result = (result*PRIME) + (this.name == null ? 43 : this.name.hashCode()); result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32)); result = (result*PRIME) + Arrays.deepHashCode(this.tags); return result; } protected boolean canEqual(Object other) { return other instanceof EqualsAndHashCodeExample; } public static class Square { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Square)) return false; Square other = (Square) o; if (!other.canEqual((Object)this)) return false; if (!super.equals(o)) return false; if (this.width != other.width) return false; if (this.height != other.height) return false; return true; } @Override public int hashCode() { final int PRIME = 59; int result = 1; result = (result*PRIME) + super.hashCode(); result = (result*PRIME) + this.width; result = (result*PRIME) + this.height; return result; } protected boolean canEqual(Object other) { return other instanceof Square; } } }
@NoArgsConstructor/@RequiredArgsConstructor/@AllArgsConstructor
@NoArgsConstructor产生一个无参构造函数,@RequiredArgsConstructor将为没有给变量生产一个只有一个参数的构造函数,@AllArgsConstructor将生成一个有所有变量的构造函数,其中的staticName属性指定生产一个静态构造函数的名称,代码如下:
@RequiredArgsConstructor(staticName = "of") @AllArgsConstructor(access = AccessLevel.PROTECTED) public class ConstructorExample<T> { private int x, y; @NonNull private T description; @NoArgsConstructor public static class NoArgsExample { @NonNull private String field; } public static void main(String[] args){ ConstructorExample<User> constructorExample1 = new ConstructorExample<User>(1, 1, new User()); ConstructorExample<User> constructorExample2 = ConstructorExample.of(new User()); } }
@Data
是 @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter在所有非final变量和@RequiredArgsConstructor的汇集功能,也就是说能为POJO类所有变量生成getters方法, 为所有非final方法生产setters, toString, equals和hashCode方法代码如下:
@Data public class DataExample { private final String name; @Setter(AccessLevel.PACKAGE) private int age; private double score; private String[] tags; @ToString(includeFieldNames=true) @Data(staticConstructor="of") public static class Exercise<T> { private final String name; private final T value; } }
@Cleanup 用于代码执行完成后自动释放资源,代码如下:
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); } } }
@Builder
引入一个复杂的构造函数,代码如下:
@Builder public class BuilderExample { @Builder.Default private long created = System.currentTimeMillis(); private String name; private int age; @Singular private Set<String> occupations; public static void main(String args){ BuilderExample.builder().created(System.currentTimeMillis()).age(30).name("jinjunzhu"); } }
还有一些不常用的变量,不一一介绍了,大家参考如下链接:
https://projectlombok.org/features/all
文中源码地址:
https://github.com/jinjunzhu/spring-boot-mybatis.git
个人公众号,欢迎关注,一起学习进步