Lombok之@With使用

一. 為什么要用?

首先wither 是在in lombok v1.18.10. 之前,在in lombok v1.18.10.之后重名為 with。with 使用場景就為克隆對象。修改一個(gè)值而保留其他值不變。

例如,如果您創(chuàng)建公共類Point {private final int x,y; },setter沒有意義,因?yàn)檫@些字段是最終字段。 @With可以為您生成一個(gè)withX(int newXValue)方法,該方法將返回一個(gè)新點(diǎn),該點(diǎn)具有x的提供值和y的相同值。

二. 如何使用?

@With 可以使用在類上,也可以使用在成員變量上。加在類上相當(dāng)于給所有成員變量 @With

@AllArgsConstructor
@With
class Test {

//    @With(AccessLevel.PUBLIC)
    private String name;
    private  String password;
    private String age;


    public static void main(String[] args) {
        System.out.println("=======");
    }
}

反編譯后的代碼如下:

public Test withName(final String name) {
    return this.name == name ? this : new Test(name, this.password, this.age);
}

public Test withPassword(final String password) {
    return this.password == password ? this : new Test(this.name, password, this.age);
}

public Test withAge(final String age) {
    return this.age == age ? this : new Test(this.name, this.password, age);
}

三. 源碼

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package lombok;

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

@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
public @interface With {
    AccessLevel value() default AccessLevel.PUBLIC;

    With.AnyAnnotation[] onMethod() default {};

    With.AnyAnnotation[] onParam() default {};

    /** @deprecated */
    @Deprecated
    @Retention(RetentionPolicy.SOURCE)
    @Target({})
    public @interface AnyAnnotation {
    }
}
  • 元注解:@Target({ElementType.TYPE, ElementType.FIELD}),

    @Retention(RetentionPolicy.SOURCE)

  • 注解屬性:AccessLevel.PUBLIC ,控制方法的訪問級別

四. 特別說明

本文已經(jīng)收錄在Lombok注解系列文章總覽中,并繼承上文中所提的特別說明

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容