• Lombok


    使用步骤

    (1)在idea中安装lombok插件

    (2)在项目中导入lombok的jar包

    1. <dependency>
    2. <groupId>org.projectlombokgroupId>
    3. <artifactId>lombokartifactId>
    4. <version>1.18.22version>
    5. dependency>

    (3)在实体类上加注解即可

    1. import lombok.AllArgsConstructor;
    2. import lombok.Data;
    3. /**
    4. * @Description: 类描述
    5. * @Author: com.gt
    6. * @Date: 2022/03/12 09:29
    7. */
    8. @Data
    9. @AllArgsConstructor
    10. public class User {
    11. private int id;
    12. private String name;
    13. private String password;
    14. }

     注解

    @Getter and @Setter
    @FieldNameConstants 字段属性常量
    @ToString
    @EqualsAndHashCode
    @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor 全部的构造参数 无参构造
    @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
    @Data 最重要的data数据
    @Builder
    @SuperBuilder
    @Singular
    @Delegate
    @Value
    @Accessors
    @Wither
    @With
    @SneakyThrows
    @val
    @var

    @Data:无参构造,get,set,tostring,hashcode,equals

    @AllArgsConstructor:有参构造

    @NoArgsConstructor:无参构造

    @EqualsAndHashCode

    @ToString

    @Getter

    简介

    • Lombok 是一个非常热门的开源项目,使用它可以有效的解决 Java 工程中那些繁琐又重复代码,例如 Setter、Getter、toString、equals、hashCode 以及非空判断等,都可以使用 Lombok 有效的解决。

    使用

    1.添加 Lombok 插件

    在 IDE 中必须安装 Lombok 插件,才能正常调用被 Lombok 修饰的代码,以 Idea 为例,添加的步骤如下:

    • 点击 File > Settings > Plugins 进入插件管理页面
    • 点击 Browse repositories...
    • 搜索 Lombok Plugin
    • 点击 Install plugin 安装插件
    • 重启 IntelliJ IDEA

    安装完成,如下图所示:

    2.添加 Lombok 库

    接下来我们需要在项目中添加最新的 Lombok 库,如果是 Maven 项目,直接在 pom.xml 中添加如下配置:

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.projectlombokgroupId>
    4. <artifactId>lombokartifactId>
    5. <version>1.18.12version>
    6. <scope>providedscope>
    7. dependency>
    8. dependencies>

    如果是 JDK 9+ 可使用模块的方式添加,配置如下:

    1. <annotationProcessorPaths>
    2. <path>
    3. <groupId>org.projectlombokgroupId>
    4. <artifactId>lombokartifactId>
    5. <version>1.18.12version>
    6. path>
    7. annotationProcessorPaths>

    3.使用 Lombok

    接下来到了前半部分中最重要的 Lombok 使用环节了,我们先来看在没有使用 Lombok 之前的代码:

    1. public class Person {
    2. private Integer id;
    3. private String name;
    4. public Integer getId() {
    5. return id;
    6. }
    7. public void setId(Integer id) {
    8. this.id = id;
    9. }
    10. public String getName() {
    11. return name;
    12. }
    13. public void setName(String name) {
    14. this.name = name;
    15. }
    16. }

    这是使用 Lombok 之后的代码:

    • 可以看出在 Lombok 之后,用一个注解就搞定了之前所有 Getter/Setter 的代码,让代码瞬间优雅了很多
    1. @Getter
    2. @Setter
    3. public class Person {
    4. private Integer id;
    5. private String name;
    6. }

    Lombok 所有注解如下:

    • val:用在局部变量前面,相当于将变量声明为 final;
    • @NonNull:给方法参数增加这个注解会自动在方法内对该参数进行是否为空的校验,如果为空,则抛出 NPE(NullPointerException);
    • @Cleanup:自动管理资源,用在局部变量之前,在当前变量范围内即将执行完毕退出之前会自动清理资源,自动生成 try-finally 这样的代码来关闭流;
    • @Getter/@Setter:用在属性上,再也不用自己手写 setter 和 getter 方法了,还可以指定访问范围;
    • @ToString:用在类上可以自动覆写 toString 方法,当然还可以加其他参数,例如 @ToString(exclude=”id”) 排除 id 属性,或者 @ToString(callSuper=true, includeFieldNames=true) 调用父类的 toString 方法,包含所有属性;
    • @EqualsAndHashCode:用在类上自动生成 equals 方法和 hashCode 方法;
    • @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor:用在类上,自动生成无参构造和使用所有参数的构造函数以及把所有 @NonNull 属性作为参数的构造函数,如果指定 staticName="of" 参数,同时还会生成一个返回类对象的静态工厂方法,比使用构造函数方便很多;
    • @Data:注解在类上,相当于同时使用了 @ToString、@EqualsAndHashCode、@Getter、@Setter 和 @RequiredArgsConstrutor 这些注解,对于 POJO 类十分有用;
    • @Value:用在类上,是 @Data 的不可变形式,相当于为属性添加 final 声明,只提供 getter 方法,而不提供 setter 方法;
    • @Builder:用在类、构造器、方法上,为你提供复杂的 builder APIs,让你可以像如下方式一样调用Person.builder().name("xxx").city("xxx").build();
    • @SneakyThrows:自动抛受检异常,而无需显式在方法上使用 throws 语句;
    • @Synchronized:用在方法上,将方法声明为同步的,并自动加锁,而锁对象是一个私有的属性 $lock 或 $LOCK,而 Java 中的 synchronized 关键字锁对象是 this,锁在 this 或者自己的类对象上存在副作用,就是你不能阻止非受控代码去锁 this 或者类对象,这可能会导致竞争条件或者其它线程错误;
    • @Getter(lazy=true):可以替代经典的 Double Check Lock 样板代码;
    • @Log:根据不同的注解生成不同类型的 log 对象,但是实例名称都是 log,有六种可选实现类
      • @CommonsLog Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);
      • @Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName());
      • @Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class);
      • @Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
      • @Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
      • @XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);

    它们的具体使用如下:

    ① val 使用

    1. val sets = new HashSet();
    2. // 相当于
    3. final Set sets = new HashSet<>();

    ② NonNull 使用

    1. public void notNullExample(@NonNull String string) {
    2. string.length();
    3. }
    4. // 相当于
    5. public void notNullExample(String string) {
    6. if (string != null) {
    7. string.length();
    8. } else {
    9. throw new NullPointerException("null");
    10. }
    11. }

    ③ Cleanup 使用

    1. public static void main(String[] args) {
    2. try {
    3. @Cleanup InputStream inputStream = new FileInputStream(args[0]);
    4. } catch (FileNotFoundException e) {
    5. e.printStackTrace();
    6. }
    7. // 相当于
    8. InputStream inputStream = null;
    9. try {
    10. inputStream = new FileInputStream(args[0]);
    11. } catch (FileNotFoundException e) {
    12. e.printStackTrace();
    13. } finally {
    14. if (inputStream != null) {
    15. try {
    16. inputStream.close();
    17. } catch (IOException e) {
    18. e.printStackTrace();
    19. }
    20. }
    21. }
    22. }

    ④ Getter/Setter 使用

    1. @Setter(AccessLevel.PUBLIC)
    2. @Getter(AccessLevel.PROTECTED)
    3. private int id;
    4. private String shap;

    ⑤ ToString 使用

    1. @ToString(exclude = "id", callSuper = true, includeFieldNames = true)
    2. public class LombokDemo {
    3. private int id;
    4. private String name;
    5. private int age;
    6. public static void main(String[] args) {
    7. // 输出 LombokDemo(super=LombokDemo@48524010, name=null, age=0)
    8. System.out.println(new LombokDemo());
    9. }
    10. }

    ⑥ EqualsAndHashCode 使用

    1. @EqualsAndHashCode(exclude = {"id", "shape"}, callSuper = false)
    2. public class LombokDemo {
    3. private int id;
    4. private String shap;
    5. }

    ⑦ NoArgsConstructor、RequiredArgsConstructor、AllArgsConstructor 使用

    1. @NoArgsConstructor
    2. @RequiredArgsConstructor(staticName = "of")
    3. @AllArgsConstructor
    4. public class LombokDemo {
    5. @NonNull
    6. private int id;
    7. @NonNull
    8. private String shap;
    9. private int age;
    10. public static void main(String[] args) {
    11. new LombokDemo(1, "Java");
    12. // 使用静态工厂方法
    13. LombokDemo.of(2, "Java");
    14. // 无参构造
    15. new LombokDemo();
    16. // 包含所有参数
    17. new LombokDemo(1, "Java", 2);
    18. }
    19. }

    ⑧ Builder 使用

    1. @Builder
    2. public class BuilderExample {
    3. private String name;
    4. private int age;
    5. @Singular
    6. private Set occupations;
    7. public static void main(String[] args) {
    8. BuilderExample test = BuilderExample.builder().age(11).name("Java").build();
    9. }
    10. }

    ⑨ SneakyThrows 使用

    1. public class ThrowsTest {
    2. @SneakyThrows()
    3. public void read() {
    4. InputStream inputStream = new FileInputStream("");
    5. }
    6. @SneakyThrows
    7. public void write() {
    8. throw new UnsupportedEncodingException();
    9. }
    10. // 相当于
    11. public void read() throws FileNotFoundException {
    12. InputStream inputStream = new FileInputStream("");
    13. }
    14. public void write() throws UnsupportedEncodingException {
    15. throw new UnsupportedEncodingException();
    16. }
    17. }

    ⑩ Synchronized 使用

    1. public class SynchronizedDemo {
    2. @Synchronized
    3. public static void hello() {
    4. System.out.println("world");
    5. }
    6. // 相当于
    7. private static final Object $LOCK = new Object[0];
    8. public static void hello() {
    9. synchronized ($LOCK) {
    10. System.out.println("world");
    11. }
    12. }
    13. }

    ⑪ Getter(lazy = true) 使用

    1. public class GetterLazyExample {
    2. @Getter(lazy = true)
    3. private final double[] cached = expensive();
    4. private double[] expensive() {
    5. double[] result = new double[1000000];
    6. for (int i = 0; i < result.length; i++) {
    7. result[i] = Math.asin(i);
    8. }
    9. return result;
    10. }
    11. }
    12. // 相当于
    13. import java.util.concurrent.atomic.AtomicReference;
    14. public class GetterLazyExample {
    15. private final AtomicReference cached = new AtomicReference<>();
    16. public double[] getCached() {
    17. java.lang.Object value = this.cached.get();
    18. if (value == null) {
    19. synchronized (this.cached) {
    20. value = this.cached.get();
    21. if (value == null) {
    22. final double[] actualValue = expensive();
    23. value = actualValue == null ? this.cached : actualValue;
    24. this.cached.set(value);
    25. }
    26. }
    27. }
    28. return (double[]) (value == this.cached ? null : value);
    29. }
    30. private double[] expensive() {
    31. double[] result = new double[1000000];
    32. for (int i = 0; i < result.length; i++) {
    33. result[i] = Math.asin(i);
    34. }
    35. return result;
    36. }
    37. }

    实现原理:

    99%的程序员都在用Lombok,原理竟然这么简单?我也手撸了一个!|建议收藏!!! - 云+社区 - 腾讯云 (tencent.com)

  • 相关阅读:
    题目 2086: 最长公共子序列
    2.3、传输方式
    13.3 GAS与属性
    2022最新Java面试笔试题目分享,Java高级工程师面试题
    java基础 --- 关键字 final、this、super、static
    Servlet表单提交、前后端数据交换、页面跳转
    Godot Identifier “File“ not declared in the current scope.
    开源LC3编解码器测试Demo
    DETR:End-to-End Object Detection with Transformers
    Tensorflow 2.x入门教程
  • 原文地址:https://blog.csdn.net/qq_46423017/article/details/126521846