1. 程式人生 > 其它 >SpringBoot - Lombok使用詳解4(@Data、@Value、@NonNull、@Cleanup)

SpringBoot - Lombok使用詳解4(@Data、@Value、@NonNull、@Cleanup)

六、Lombok 註解詳解(3)

8,@Data

(1)@Data是一個複合註解,用在類上,使用後會生成:預設的無參建構函式、所有屬性的getter、所有非final屬性的setter方法,並重寫toString、equals、hashcode方法。
import lombok.Data;
 
@Data
public class User {
    private String name;
    private Integer age;
}

(2)上面的@Data等效於如下幾個註解結合使用:

import lombok.*;
 
@Setter
@Getter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
public class User { private String name; private Integer age; }

9,@Value

@Value註解和@Data類似,區別在於它會把所有成員變數預設定義為private final修飾,並且不會生成set()方法。
// 使用註解
@Value
public class ValueExample {
    String name;
    @Wither(AccessLevel.PACKAGE) @NonFinal int age;
    double score;
    protected String[] tags;
}
 
// 不使用註解 public final class ValueExample { private final String name; private int age; private final double score; protected final String[] tags; public ValueExample(String name, int age, double score, String[] tags) { this.name = name; this.age = age; this
.score = score; this.tags = tags; } //下面省略了其它方法 //..... }

10,@NonNull

(1)註解在屬性上,標識屬性是不能為空,為空則丟擲異常。換句話說就是進行空值檢查。
import lombok.NonNull;
 
public class NonNullExample {
    private String name;
 
    public NonNullExample(@NonNull User user) {
        this.name = user.getName();
    }
}

(2)上面相當與如下Java程式碼:

public class NonNullExample {
    private String name;
 
    public NonNullExample(User user) {
        if (user == null) {
            throw new NullPointerException("user");
        }
        this.name = user.getName();
    }
}

(3)下面是一個簡單的測試樣例:

User user = null;
try {
    NonNullExample example = new NonNullExample(user);
}catch (NullPointerException ex) {
    return ex.toString();
}

11,@Cleanup

(1)用於關閉並釋放資源,可以用在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);
        }
    }
}

(2)上面相當與如下傳統的Java程式碼:

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();
      }
    }
  }
}
早年同窗始相知,三載瞬逝情卻萌。年少不知愁滋味,猶讀紅豆生南國。別離方知相思苦,心田紅豆根以生。