欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java中@RequiredArgsConstructor注解的基本用法

 更新時間:2024年09月04日 10:30:35   作者:碼農(nóng)研究僧  
這篇文章主要介紹了Java中@RequiredArgsConstructor注解的基本用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

前言

從源碼中學習,事因是看到項目代碼中有所引用

@RequiredArgsConstructor 是 Lombok 提供的一個注解,用于自動生成一個包含所有 final 字段和帶有 @NonNull 注解字段的構造函數(shù)

這可以減少樣板代碼,尤其是在需要依賴注入時

1. 基本知識

Lombok 是一個 Java 庫,通過注解簡化代碼

常用注解包括 @Getter, @Setter, @ToString, @EqualsAndHashCode, 和 @Data 等

針對@RequiredArgsConstructor 注解會生成一個包含所有 final 字段和帶有 @NonNull 注解字段的構造函數(shù) 

這對于構造必須初始化這些字段的對象非常有用

基本的語法如下:

@RequiredArgsConstructor
public class MyClass {
    private final String name;
    private final int age;
    private String address;
    
    @NonNull
    private String phoneNumber;
}

對應生成的構造函數(shù)如下:

public MyClass(String name, int age, String phoneNumber) {
    this.name = name;
    this.age = age;
    this.phoneNumber = phoneNumber;
}

對應需要注意的事項如下:

  • 字段的順序:生成的構造函數(shù)中的參數(shù)順序是按照字段在類中定義的順序
  • @NonNull 注解:如果某個字段帶有 @NonNull 注解,它也會包含在構造函數(shù)中,即使它不是 final 的。

與其他構造函數(shù)沖突:如果手動定義了構造函數(shù),@RequiredArgsConstructor 生成的構造函數(shù)可能會與其沖突

與其他注解比較:

  • @NoArgsConstructor:生成一個無參構造函數(shù)。
  • @AllArgsConstructor:生成一個包含所有字段(包括非 final 字段)的構造函數(shù)

2. 源碼解讀

先看源碼的對應屬性

對應的屬性分析如下:

staticName:

  • 設置了這個屬性,會生成一個靜態(tài)方法,該方法調用私有構造函數(shù)
  • 這個靜態(tài)方法主要用于推斷類型參數(shù)

onConstructor:

  • 允許在生成的構造函數(shù)上添加指定的注解
  • JDK 7 和 JDK 8 的語法稍有不同。

access:

  • 設置構造函數(shù)的訪問級別
  • 默認是 public,可以設置為 private, protected 或 package

針對源碼結合以下Demo進行展示

3. Demo

3.1 簡易Demo

import lombok.NonNull;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class test {
    private final String firstName;
    private final String lastName;
    @NonNull
    private String email;
    private int age;

    public static void main(String[] args) {
        // 正確使用示例
        test person = new test("碼農(nóng)", "研究僧", "https://blog.csdn.net/weixin_47872288");
        System.out.println("Person created: " + person);

        // 錯誤使用示例(會導致編譯錯誤)
        // Person person2 = new Person("Jane", "Doe");
    }

    @Override
    public String toString() {
        return "Person{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

明確需要3個屬性,不可超過4個

再者對應的字段屬性是按照順序的,如果更換順序會出現(xiàn)如下場景:

test person = new test("碼農(nóng)","https://blog.csdn.net/weixin_47872288","研究僧");

3.2 staticName屬性

@RequiredArgsConstructor(staticName = "of") 

會生成一個靜態(tài)方法 of 來實例化對象,而不是直接調用構造函數(shù)

import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor(staticName = "of")
public class test {
    private final String firstName;

    private final String lastName;
    private final String email;

    public static void main(String[] args) {
        test example = test.of("碼農(nóng)","研究僧","https://blog.csdn.net/weixin_47872288");
        System.out.println(example);
    }

    @Override
    public String toString() {
        return "StaticConstructorExample{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

截圖如下:

3.3 onConstructor屬性

@RequiredArgsConstructor(onConstructor_ = @__(@CustomAnnotation("Custom Constructor"))) 

會在生成的構造函數(shù)上添加 @CustomAnnotation

import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
    String value();
}
@RequiredArgsConstructor(onConstructor_ = @__(@CustomAnnotation("Custom Constructor")))
public class test {
    private final String firstName;

    private final String lastName;
    private final String email;

    public static void main(String[] args) {
        test example = new test("碼農(nóng)","研究僧","https://blog.csdn.net/weixin_47872288");
        System.out.println(example);
    }

    @Override
    public String toString() {
        return "StaticConstructorExample{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

3.4 access屬性

@RequiredArgsConstructor(access = AccessLevel.PRIVATE, staticName = "of")
public class test {
    private final String firstName;

    private final String lastName;
    private final String email;

    public static void main(String[] args) {
        test example = test.of("碼農(nóng)", "研究僧", "https://blog.csdn.net/weixin_47872288");
        System.out.println(example);
    }

    @Override
    public String toString() {
        return "StaticConstructorExample{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

不需要構造函數(shù)是私有的,可以將構造函數(shù)的訪問級別設置為 public 或 protected,直接進行new

但是我的private它竟然可以new(神奇=-=)

4. @AllArgsConstructor比較

使用 @RequiredArgsConstructor 時,只有 final 字段和 @NonNull 字段會被初始化

但是@AllArgsConstructor 生成一個構造函數(shù),該構造函數(shù)包含類中所有字段,無論它們是否為 final 或帶有 @NonNull 注解

@AllArgsConstructor
public class test {
    private final String firstName;
    private  String lastName;
    @NonNull
    private String email;
    private int age;

    public static void main(String[] args) {
        // 正確使用示例
        test person = new test("碼農(nóng)","研究僧","https://blog.csdn.net/weixin_47872288",18);
        System.out.println("Person created: " + person);

        // 錯誤使用示例(會導致編譯錯誤)
        // Person person2 = new Person("Jane", "Doe");
    }

    @Override
    public String toString() {
        return "Person{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

截圖如下:(必須要有四個參數(shù))

這兩者都可以實用構造函數(shù)注入,但推薦使用@RequiredArgsConstructor,因為它只會初始化那些在創(chuàng)建對象時必需的字段

總結

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論