Lombok之@With使用

一. 为什么要用?

首先wither 是在in lombok v1.18.10. 之前,在in lombok v1.18.10.之后重名为 with。with 使用场景就为克隆对象。修改一个值而保留其他值不变。

例如,如果您创建公共类Point {private final int x,y; },setter没有意义,因为这些字段是最终字段。 @With可以为您生成一个withX(int newXValue)方法,该方法将返回一个新点,该点具有x的提供值和y的相同值。

二. 如何使用?

@With 可以使用在类上,也可以使用在成员变量上。加在类上相当于给所有成员变量 @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 ,控制方法的访问级别

四. 特别说明

本文已经收录在Lombok注解系列文章总览中,并继承上文中所提的特别说明

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。