likes
comments
collection

Lombok没有那么简单

作者站长头像
站长
· 阅读数 33

Lombok

Lombok很多人都用到了,但网上对他的介绍大多数都是什么呢能自动生成GetSet方法 而实际的Lombok并没有那么简单,下面给大家介绍一下Lombok冷门但实用的各种功能.

自动判空@NonNull

可以注释在方法参数上或者字段上 如果注释在方法参数上会在方法的第一行添加下面的语句 例子:

public void a(@NonNull List<String> staffIdList, @NonNull String applyFormId, @NonNull String applyFormNo) 

会生成:

    public void a(@NonNull List<String> staffIdList, @NonNull String applyFormId, @NonNull String applyFormNo) {
        if (staffIdList == null) {
            throw new NullPointerException("staffIdList is marked non-null but is null");
        } else if (applyFormId == null) {
            throw new NullPointerException("applyFormId is marked non-null but is null");
        } else if (applyFormNo == null) {
            throw new NullPointerException("applyFormNo is marked non-null but is null");
		}

如果加到字段上,会给所有为该字段赋值的地方都添加判空语句 例子:

 @NonNull
 private String id;

会生成

 public 构造方法(@NonNull final String id) {
        if (id == null) {
            throw new NullPointerException("id is marked non-null but is null");
 public void set方法(@NonNull final String id) {
        if (id == null) {
            throw new NullPointerException("id is marked non-null but is null");

自动close资源流@Cleanup

它可以注释在我们的局部变量前,功能是将被注释的变量自动进行try-finally包裹,并调用他的close方法 例子:

public void copyFile(String in, String out) throws IOException {
      @Cleanup FileInputStream inStream = new FileInputStream(in);
      @Cleanup FileOutputStream outStream = new FileOutputStream(out);
      byte[] b = new byte[65536];
      while (true) {
          int r = inStream.read(b);
          if (r == -1) break;
          outStream.write(b, 0, r);
      }
  }

会生成如下代码

public void copyFile(String in, String out) throws IOException {
      @Cleanup FileInputStream inStream = new FileInputStream(in);
      try {
          @Cleanup FileOutputStream outStream = new FileOutputStream(out);
          try {
              byte[] b = new byte[65536];
              while (true) {
                  int r = inStream.read(b);
                  if (r == -1) break;
                  outStream.write(b, 0, r);
              }
          } finally {
              if (outStream != null) outStream.close();
          }
      } finally {
          if (inStream != null) inStream.close();
      }
  }

任何变量类型 val/var

可以用于定义任何变量,注意这个不用加@ 例子:

    val list =new ArrayList<String>();
    list.toArray()

会生成:

        ArrayList<String> list = new ArrayList();
        list.toArray();

链式构造对象@Builder

可以注释在类上面,可以使用类Builder来方便的构造对象 例子:

@Builder
  class Example<T> {
  	private T foo;
  	private final String bar;
  }

会生成:

class Example<T> {
  	private T foo;
  	private final String bar;
  	
  	private Example(T foo, String bar) {
  		this.foo = foo;
  		this.bar = bar;
  	}
  	
  	public static <T> ExampleBuilder<T> builder() {
  		return new ExampleBuilder<T>();
  	}
  	
  	public static class ExampleBuilder<T> {
  		private T foo;
  		private String bar;
  		
  		private ExampleBuilder() {}
  		
  		public ExampleBuilder foo(T foo) {
  			this.foo = foo;
  			return this;
  		}
  		
  		public ExampleBuilder bar(String bar) {
  			this.bar = bar;
  			return this;
  		}
  		
  		@java.lang.Override public String toString() {
  			return "ExampleBuilder(foo = " + foo + ", bar = " + bar + ")";
  		}
  		
  		public Example build() {
  			return new Example(foo, bar);
  		}
  	}
  }

使用:

 Example build = Example.builder().foo(1).bar("").build();

即可方便的build一个对象

自动生成log对象 @Slf4j/@Log4j/@JBossLog

可以自动生成打日志使用的log对象,支持主流日志框架 使用:

 @Slf4j
  public class LogExample {
  }

会生成:

  public class LogExample {
      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
  }

如果想使用Log4j的log对象,注释换为@Log4j即可

自动catch异常 @SneakyThrows

可以注释在方法上,可以自动catch掉所有已检查异常 使用:

  @SneakyThrows(UnsupportedEncodingException.class)
  public void utf8ToString(byte[] bytes) {
      return new String(bytes, "UTF-8");
  }

会生成

public void utf8ToString(byte[] bytes) {
      try {
          return new String(bytes, "UTF-8");
      } catch (UnsupportedEncodingException $uniqueName) {
          throw useMagicTrickeryToHideThisFromTheCompiler($uniqueName);
          // This trickery involves a bytecode transformer run automatically during the final stages of compilation;
          // there is no runtime dependency on lombok.
      }