Java lombok 的使用

功能介绍

lombok 是一个可以通过注解的形式来代替一些 Java 代码。

地址

https://projectlombok.org/features/all

使用

  1. Maven 添加依赖
<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.10</version>
    </dependency>
</dependencies>
  1. 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);
    }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容