Lombok不常见但实用的注解

资料参考地址1:@SneakyThrows注解

资料参考地址2: Lombok之@Cleanup使用

资料参考地址3: lombok 实验性注解之 @UtilityClass

@SneakyThrows

为了消除遇到Exception异常时必须try catch 或向上抛处理的模板代码

示例代码

import lombok.SneakyThrows;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * SneakyThrows是为了消除这样的模板代码
 * https://blog.csdn.net/qq_22162093/article/details/115486647
 * @author : lyn
 */
public class SneakyThrowsTest {

    /**
     * 使用前必须用try catch 包一层
     */
    private Date strToDate1(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(str);
        } catch (ParseException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 使用@SneakyThrows后简洁了很多
     */
    @SneakyThrows
    private Date strToDate2(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(str);
    }
}

@UtilityClass

作用于类,将类标记为 final,并且类、内部类中的方法、字段都标记为 static

并私有了构造方法,一般用在工具类上

编译前

@UtilityClass
public class UtilityClassTest {
    private String name;
    public void methodOne(){
        System.out.println("");
    }
}

编译后

public final class UtilityClassTest {
  private static String name;
  
  private UtilityClassTest() {
    throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
  }
  
  public static void methodOne() {
    System.out.println("");
  }
}

@Cleanup

清理流对象,不用手动去关闭流,多么优雅

编译前

 @Cleanup Reader fileReader = new FileReader("D:\\code.txt");

编译后

    try {
      Reader fileReader = new FileReader("D:\\code.txt");
      if (Collections.<Reader>singletonList(fileReader).get(0) != null)
        fileReader.close(); 
    } catch (Throwable $ex) {
      throw $ex;
    } 

Collections.singletonList被限定只被分配一个内存空间,也就是只能存放一个元素的内容

Collections.singletonList的作用和使用方法

@AllArgsConstructor

与private final 结合使用

替代@Autowired构造注入,多个bean 注入时更加清晰,但有循环依赖的问题

@AllArgsConstructor 
@Slf4j
@Component
@AllArgsConstructor
public class CustomAuthenticationSuccessEventHandler implements AuthenticationSuccessHandler {

   private final OperationLogHandler operationLogHandler;

}
posted @ 2022-10-29 20:05  进击的小蔡鸟  阅读(197)  评论(0编辑  收藏  举报