功能介绍
lombok 是一个可以通过注解的形式来代替一些 Java 代码。
地址
https://projectlombok.org/features/all
使用
- Maven 添加依赖
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
- Intellij idea开发的话需要安装Lombok plugin(setting -> Plugin -> lombok),同时设置 Setting -> Compiler -> Annotation Processors -> Enable annotation processing勾选。
lombok 注解
Data
注解在类上,为类所有的属性提供getting / setting 和 toString 的方法。
这个装饰器便捷的地方在于,如果修改了某个属性的类型或名称,不同再去改对应的get/set 方法
@NonNull
you can use @NonNull on the parameter of a method or constructor to have lombok generate a null-check statement for you.
import lombok.NonNull;
public class LombokTest{
public void method1(@NonNull String a){
System.out.println(a);
}
}
@Slf4j
@Slf4j, 使用Slf4j 日志
val
you can use val as the type of a local variable declaration instead of actually writing the type.
import lombok.val;
public class ValExample{
public void example2(){
val map = new HashMap<Integer,String>();
for(val m : map.entrySet()){
System.out.printf(m);
}
}
}
var
var works exactly like val,except the local vaiable is not marked as final.类型将由初始化变量决定。
@Cleanup
You can use @Cleanup to ensure a give resource is automatically cleaned up before the code execution path exists your current scope.
import lombok.Cleanup;
import java.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);
}
}
}