Lombok是一个可以通过简单的注解形式来帮助我们简化消除一些必须有但显得很臃肿的Java代码的工具,通过使用对应的注解,可以在编译源码的时候生成对应的方法。
官方地址:https://projectlombok.org/
github地址:https://github.com/rzwitserloot/lombok
在IntelliJ IDEA 中的使用
(1)先安装lombok插件,步骤如下。
- 菜单 File > Settings > Plugins;
- 点击 Browse repositories... 按钮;
- 搜索 Lombok 插件;
- 点击 Install plugin或者Update(更新);
- 重启 IntelliJ IDEA;
![cc63b9cca0567cc1f3744dfd73d29ad6.png](https://img-blog.csdnimg.cn/img_convert/cc63b9cca0567cc1f3744dfd73d29ad6.png)
(2)然后在项目中引入lombok的jar包
引入lombok 1.18.8 最新版jar包。
org.projectlombok
lombok
1.18.8
provided
Lombok的scope=provided,说明它只在编译阶段生效,不需要打入包中。事实正是如此,Lombok在编译期将带Lombok注解的Java文件正确编译为完整的Class文件。
Lombok用法
Lombok注解说明:
val:用在局部变量前面,相当于将变量声明为final。
public static void main( String[] args )
{
System.out.println( "Hello World!" );
val sets = new HashSet();
val lists = new ArrayList();
val maps = new HashMap();
//=>相当于如下
final Set sets2 = new HashSet<>();
final List lists2 = new ArrayList<>();
final Map maps2 = new HashMap<>();
}
@NonNull:给方法参数增加这个注解会自动在方法内对该参数进行是否为空的校验,如果为空,则抛出NPE(NullPointerException)。
public void notNullExample(@NonNull String string) {
string.length();
}
//=>相当于
public void notNullExample2(String string) {
if (string != null) {
string.length();
} else {
throw new NullPointerException("null");
}
}
@Cleanup:自动管理资源,用在局部变量之前,在当前变量范围内即将执行完毕退出之前会自动清理资源,自动生成try-finally这样的代码来关闭流。
public static void main( String[] args ) throws Exception
{
try {
@Cleanup InputStream inputStream = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//=>相当于
InputStream inputStream = null;
try {
inputStream = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Getter/@Setter:用在属性上,再也不用自己手写setter和getter方法了,还可以指定访问范围。
public class Person {
@Setter(AccessLevel.PUBLIC)
@Getter(AccessLevel.PROTECTED)
private int id;
private String name;
}
在IntelliJ中按下Ctrl+F12快捷键,就可以看到Lombok 自动生成了一系列的方法。
![faeebbd78af34ef1db27ce22d4e9e184.png](https://img-blog.csdnimg.cn/img_convert/faeebbd78af34ef1db27ce22d4e9e184.png)
@ToString:用在类上,可以自动覆写toString方法,当然还可以加其他参数,例如@ToString(exclude=”id”)排除id属性,或者@ToString(callSuper=true, includeFieldNames=true)调用父类的toString方法,包含所有属性。
@ToString(exclude = "id