一. 為什么要用?
首先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注解系列文章總覽中,并繼承上文中所提的特別說明