Lombok的使用

Lombok是一个Java库,它通过注解自动为类生成构造器、getter/setter、equals、hashcode和toString方法,避免手动编写这些常见代码。本文介绍了@Data、@Getter/@Setter、@NonNull、@Cleanup、@EqualsAndHashCode和@ToString等注解的使用,并给出了不使用Lombok时的代码示例。
摘要由CSDN通过智能技术生成

Lombok能通过注解的方式,在编译时自动为属性生成构造器、getter/setter、equals、hashcode、toString方法。出现的神奇就是在源码中没有getter和setter方法,但是在编译生成的字节码文件中有getter和setter方法。这样就省去了手动重建这些代码的麻烦,使代码看起来更简洁些。

Lombok的使用跟引用jar包一样,可以在官网(https://projectlombok.org/download)下载jar包,也可以使用maven添加依赖:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
    <scope>provided</scope>
</dependency>

@Data

@Data注解在类上,会为类的所有属性自动生成setter/getterequalscanEqualhashCodetoString方法,如为final属性,则不会为该属性生成setter方法。

官方实例如下:

import lombok.AccessLevel;
import lombok.Setter;
import lombok.Data;
import lombok.ToString;

@Data 
public class DataExample {
   
  private final String name;
  @Setter(AccessLevel.PACKAGE) private int age;
  private double score;
  private String[] tags;
  
  @ToString(includeFieldNames=true)
  @Data(staticConstructor="of")
  public static class Exercise<T> {
   
    private final String name;
    private final T value;
  }
}

如不使用Lombok,则实现如下:

import java.util.Arrays;

public class DataExample {
   
  private final String name;
  private int age;
  private double score;
  private String[] tags;
  
  public DataExample(String name) {
   
    this.name = name;
  }
  
  public String getName() {
   
    return this.name;
  }
  
  void setAge(int age) {
   
    this.age = age;
  }
  
  public int getAge() {
   
    return this.age;
  }
  
  public void setScore(double score) {
   
    this.score = score;
  }
  
  public double getScore() {
   
    return this.score;
  }
  
  public String[] getTags() {
   
    return this.tags;
  }
  
  public void setTags(String[] tags) {
   
    this.tags = tags;
  }
  
  @Override public String toString() {
   
    return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")";
  }
  
  protected boolean canEqual(Object other) {
   
    return other instanceof DataExample;
  }
  
  @Override public boolean equals(Object o) {
   
    if (o == this) return true;
    if (!(o instanceof DataExample)) return false;
    DataExample other = (DataExample) o;
    if (!other.canEqual((Object)this)) return false;
    if (this.getName() == null ? other.getName() != null : !this.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值