Lombok使用3:其他注解

本篇文章会讲到:@NonNull、@Cleanup、@UtilityClass、@Log、@SneakyThrows、@Synchronized 注解使用

1、@NonNull使用

  • @NonNull文档官方地址

  •  注解在属性上,标识属性是不能为空,为空则抛出异常。

    import lombok.NonNull;

    public class Example {

    private String name;
    
    public Example(@NonNull User user) {
        this.name = user.getName();
    }
    

    }

 编译后:

public class Example {

    private String name;

    public Example(User user) {
        if (user == null) {
            throw new NullPointerException("user");
        }
        this.name = user.getName();
    }

}

2、@Cleanup使用

  • @Cleanup官方文档地址

  • 关闭并释放资源,可以用在 IO 流上

    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); } } }

 编译后:

import java.io.*;

public class CleanupExample {
  public static void main(String[] args) throws 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 == -1) break;
          out.write(b, 0, r);
        }
      } finally {
        if (out != null) {
          out.close();
        }
      }
    } finally {
      if (in != null) {
        in.close();
      }
    }
  }
}

3、@UtilityClass使用

  • @UtilityClass官方文档地址

  • 注解在类似,所有成员变量和内部类都为标准static静态的。

    import lombok.experimental.UtilityClass;

    @UtilityClass public class UtilityClassExample { private final int CONSTANT = 5;

    public int addSomething(int in) { return in + CONSTANT; } }

编译为:

public final class UtilityClassExample {
  private static final int CONSTANT = 5;

  private UtilityClassExample() {
    throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated");
  }

  public static int addSomething(int in) {
    return in + CONSTANT;
  }
}

4、@Log使用

  • @Log官方文档地址

  • 该注解用在类上,可以省去从日志工厂生成日志对象这一步,直接进行日志记录。 

    import lombok.extern.java.Log;

    @Log public class Example {

    public static void main(String[] args) {
        log.severe("Something's wrong here");
    }
    

    }

 编译后:

public class Example {

    private static final java.util.logging.Logger log =
            java.util.logging.Logger.getLogger(Example.class.getName());

    public static void main(String... args) {
        log.severe("Something's wrong here");
    }

}

我们也可以在注解中使用 topic 来指定生成 log 对象时的类名。

@CommonsLog
private static final org.apache.commons.logging.Log log =
        org.apache.commons.logging.LogFactory.getLog(LogExample.class);
 
@JBossLog
private static final org.jboss.logging.Logger log =
        org.jboss.logging.Logger.getLogger(LogExample.class);
 
@Log
private static final java.util.logging.Logger log =
        java.util.logging.Logger.getLogger(LogExample.class.getName());
 
@Log4j
private static final org.apache.log4j.Logger log =
        org.apache.log4j.Logger.getLogger(LogExample.class);
 
@Log4j2
private static final org.apache.logging.log4j.Logger log =
        org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
 
@Slf4j
private static final org.slf4j.Logger log =
        org.slf4j.LoggerFactory.getLogger(LogExample.class);
 
@XSlf4j
private static final org.slf4j.ext.XLogger log =
        org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);

5、@SneakyThrows使用

  • @SneakyThrows官方文档地址

  • 该注解用在方法上,可以将方法中的代码用 try-catch 语句包裹起来,捕获异常并在 catch 中用 Lombok.sneakyThrow(e) 把异常抛出。

  • 也可以使用 @SneakyThrows(Exception.class) 的形式指定抛出哪种异常。

    import lombok.SneakyThrows;

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

    @SneakyThrows public void run() { throw new Throwable(); } }

编译后:

import lombok.Lombok;

public class SneakyThrowsExample implements Runnable {
  public String utf8ToString(byte[] bytes) {
    try {
      return new String(bytes, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw Lombok.sneakyThrow(e);
    }
  }
  
  public void run() {
    try {
      throw new Throwable();
    } catch (Throwable t) {
      throw Lombok.sneakyThrow(t);
    }
  }
}

6、@Synchronized使用

  • @Synchronized官方文档地址

  • 该注解用在类方法或者实例方法上,效果和 synchronized 关键字相同,区别在于锁对象不同。

  • synchronized 关键字的锁对象分别是“类的 class 对象”和“this 对象”。

  • @Synchronized 的锁对象分别是“私有静态 final 对象 lock”和“私有 final 对象 lock”。当然,也可以自己指定锁对象。

    import lombok.Synchronized;

    public class SynchronizedExample { private final Object readLock = new Object();

    @Synchronized public static void hello() { System.out.println("world"); }

    @Synchronized public int answerToLife() { return 42; }

    @Synchronized("readLock") public void foo() { System.out.println("bar"); } }

编译后:

public class SynchronizedExample {
  private static final Object $LOCK = new Object[0];
  private final Object $lock = new Object[0];
  private final Object readLock = new Object();
  
  public static void hello() {
    synchronized($LOCK) {
      System.out.println("world");
    }
  }
  
  public int answerToLife() {
    synchronized($lock) {
      return 42;
    }
  }
  
  public void foo() {
    synchronized(readLock) {
      System.out.println("bar");
    }
  }
}

更多阅读

评论

暂无评论