Lombok 常用的注解

此文用于介绍lombok的常用用法,例如@NonNull,@Cleanup等等。

@NonNull

配置信息

lombok.nonNull.exceptionType = [NullPointerException | IllegalArgumentException | JDK | Guava | Assertion] (default: NullPointerException).

import lombok.NonNull;

public class NonNullExample extends Something {
  private String name;
  
  public NonNullExample(@NonNull Person person) {
    super(“Hello”);
    this.name = person.getName();
  }
}

import lombok.NonNull;

public class NonNullExample extends Something {
  private String name;
  
  public NonNullExample(@NonNull Person person) {
    super(“Hello”);
    if (person == null) {
      throw new NullPointerException(“person is marked @NonNull but is null”);
    }
    this.name = person.getName();
  }
}

@Cleanup

import lombok.Cleanup;
import java.io.*;
public class CleanupExample {
  public static void main(String[] argsthrows 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 == –1break;
      out.write(b, 0, r);
    }
  }
}
import java.io.*;

public class CleanupExample {
  public static void main(String[] argsthrows IOException {
    InputStream in = new FileInputStream(args[0]);
    try {
      OutputStream out = new FileOutputStream(args[1]);
      try {
        byte[] b = new byte[10000];
        while (true) {
          int r = in.read(b);
          if (r == –1break;
          out.write(b, 0, r);
        }
      finally {
        if (out != null) {
          out.close();
        }
      }
    finally {
      if (in != null) {
        in.close();
      }
    }
  }
}

@Getter/@Setter

配置Boolean类型的getter方法

lombok.getter.noIsPrefix = [true | false] (default: false)

@Data

@Value

@Builder

@SneakyThrows