lombok插件的使用(简化Java代码)
  1. 先安装插件

img

  1. 导入lombok包。如果使用maven构建项目直接在pom.xml中导入下面依赖即可
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
    <scope>provided</scope>
</dependency>
  1. 使用:直接在类的上面加注解以@Data为例
import lombok.Data;

@Data
public class People {
    private int id;
    private String username;
    private int age;
}

​ 可以看到类的结构中多了很多东西。就是注解的作用

image-20210915223832686

  1. 其他注解(官网)

    @NonNull

    or: How I learned to stop worrying and love the NullPointerException.

    @Cleanup

    Automatic resource management: Call your close() methods safely with no hassle.

    @Getter/@Setter

    Never write public int getFoo() {return foo;} again.

    @ToString

    No need to start a debugger to see your fields: Just let lombok generate a toString for you!

    @EqualsAndHashCode

    Equality made easy: Generates hashCode and equals implementations from the fields of your object..

    @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor

    Constructors made to order: Generates constructors that take no arguments, one argument per final / non-nullfield, or one argument for every field.

    @Data

    All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor!

    @Value

    Immutable classes made very easy.

    @Builder

    ... and Bob's your uncle: No-hassle fancy-pants APIs for object creation!

    @SneakyThrows

    To boldly throw checked exceptions where no one has thrown them before!

    @Synchronized

    synchronized done right: Don't expose your locks.

    @With

    Immutable 'setters' - methods that create a clone but with one changed field.

    @Getter(lazy=true)

    Laziness is a virtue!

    @Log

    Captain's Log, stardate 24435.7: "What was that line again?"

    experimental

    Head to the lab: The new stuff we're working on.

    1. 缺点
  • 代码可读性降低
  • 不支持构造器的重载
  • 非结构性减轻开发任务。
posted on 2021-09-15 23:17  需要多勇敢  阅读(166)  评论(0)    收藏  举报