lombok插件的使用,超级详细

本文详细介绍了Lombok插件的安装与使用方法,包括val、@NonNull、@Cleanup、@Getter/@Setter、@ToString、@EqualsAndHashCode、@NoArgsConstructor等注解的原理和应用示例,帮助开发者提高代码效率,减少冗余代码。
摘要由CSDN通过智能技术生成

1.添加Lombok插件

IDEA中找到setting->plugins搜索Lombok Plugin,点击install,完成安装之后重启IDEA;

2.在maven项目的pom.xml中配置

<dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${org.projectlombok.lombok.version}</version>
</dependency>

3.配置后就可以使用lombok了

val(这不是注解)
可以使用val来声明任意类型,来接收返回值,却不需要创建这个类。这样我们就不用为了接受一个数据而去专门为它写一个类;
使用方法:

import java.util.ArrayList;
import java.util.HashMap;
import lombok.val;     //首先要导包

public class ValExample {
   
  public String example() {
   
    val example = new ArrayList<String>();    //导包之后,就可以使用val来创建对象,来接受任意的数据了;
    example.add("Hello, World!");
    val foo = example.get(0);
    return foo.toLowerCase();
  }
  
  public void example2() {
   
    val map = new HashMap<Integer, String>();
    map.put(0, "zero");
    map.put(5, "five");
    for (val entry : map.entrySet()) {
   
      System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
    }
  }
}

原理:val实际上是某种“类型”,并在lombok包中作为真实类存在。必须导入它以使val起作用(或lombok.val用作类型)。局部变量声明中此类型的存在会触发final关键字的添加以及复制覆盖“ fake” val类型的初始化表达式的类型。1.16.20版本之后,就不再是final的了。
上面的代码相当于

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class ValExample {
   
  public String example() {
   
    final ArrayList<String> example = new ArrayList<String>();
    example.add("Hello, World!");
    final String foo = example.get(0);
    return foo.toLowerCase();
  }
  public void example2() {
   
    final HashMap<Integer, String> map = new HashMap<Integer, String>();
    map.put(0, "zero");
    map.put(5, "five");
    for (final Map.Entry<Integer, String> entry : map.entrySet()) {
   
      System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
    }
  }
}

@NonNull可以在方法或者构造函数上使用,可以帮我们生成空检查语句,如下面的例子:

import lombok.NonNull;

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

它就相当于下面的代码:

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


Cleanup
用来确保在代码执行路径退出当前作用域之前自动清除给定资源。可以使用@Cleanup对任何局部变量声明进行注释:

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

@Getter @Setter

可以使用@Getter和/或注释任何字段@Setter,以使lombok自动生成默认的getter / setter。

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

public class GetterSetterExample {
   
  /**
   * Age of the person. Water is wet.
   * 
   * @param age New value for this person's age. Sky is blue.
   * @return The current value of this person's age. Circles are round.
   */
  @Getter @Setter private int age = 10;

  /**
   * Name of the person.
   * -- SETTER --
   * Changes the name of this person.
   * 
   * @param name The new value.
   */
  @Setter(AccessLevel.PROTECTED) private String name;

  @Override public String toString() {
   
    return String.format("%s (age: %d)", name, age);
  }
}

等同于

public class GetterSetterExample {
   
  /**
   * Age of the person. Water is wet.
   */
  private int age = 10;

  /**
   * Name of the person.
   */
  private String name;

  @Override public String toString() {
   
    return String.format("%s (age: %d)", name, age);
  }

  /**
   * Age of the person. Water is wet.
   *
   * @return The current value of this person's age. Circles are round.
   */
  public int getAge() {
   
    return age;
  }

  /**
   * Age of the person. Water is wet.
   *
   * @param age New value for this person's age. Sky is blue.
   */
  public void setAge(int age) {
   
    this.age = age;
  }

  /**
   * Changes the name of this person.
   *
   * @param name The new value.
   */
  protected void setName(String name) {
   
    this.name = name;
  }
}

@ToString
可以对任何类定义进行注释,@ToString以使lombok生成该toString()方法的实现。默认情况下,它将按顺序打印类名称以及每个字段,并以逗号分隔。

import lombok.ToString;

@ToString
public class ToStringExample {
   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值