java lombok框架

@Data 的作用?

使用这个注解,就不用再去手写Getter,Setter,equals,canEqual,hasCode,toString等方法了,注解后在编译时会自动加进去。

@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor

@NoArgsConstructor:生成无参构造函数
@RequiredArgsConstructor:生成一个构造函数,并对打了@NonNull的参数进行NullPointer检查 (这里有坑?为啥?)
例如:

// 源代码
@RequiredArgsConstructor(staticName = "of")
class Car{
    @NonNull
    private String origin;
    @NonNull
    private String model;
}
// 编译后代码
class Car{
    @NonNull
    private String origin;
    @NonNull
    private String model;
    
    // 省略get、set方法
    private Car(@NonNull String origin, @NonNull String model) {
        if (origin == null) {
            throw new NullPointerException("origin is marked @NonNull but is null");
        } else {
            this.origin = origin;
        }
        if (model == null) {
            throw new NullPointerException("model is marked @NonNull but is null");
        } else {
            this.model = model;
        }
    }
    public static Car of(@NonNull String origin, @NonNull String model) {
        return new Car(origin, model);
    }
}

@AllArgsConstructor:生成全参构造函数

@NoArgsConstructor will generate a constructor with no parameters. If
this is not possible (because of final fields), a compiler error will
result instead, unless @NoArgsConstructor(force = true) is used, then
all final fields are initialized with 0 / false / null. For fields
with constraints, such as @NonNull fields, no check is generated,so be
aware that these constraints will generally not be fulfilled until
those fields are properly initialized later. This annotation is useful
primarily in combination with either @Data or one of the other
constructor generating annotations.

lombok还有什么常见用法?

上面的@Data、@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor都是lombok的注解。
其他还有:

@builder有什么用?

当一个类的属性很多,但构造时只需要其中几个属性时,更方便。

@builder的原理是什么

@builder自动实现了以下原生的builder模式

class Car{
    private String origin;
    private String model;

    private Car(String model){
        this.model = model;
    }

    private Car(Builder builder){
        this.origin = builder.origin;
        this.model = builder.model;
    }

    public static Car of(String model){
        return new Car(model);
    }

    public static Builder builder(){
        return new Builder();
    }

    public static class Builder{
        private String origin;
        private String model;

        public Builder origin(String origin){
            this.origin = origin;
            return this;
        }

        public Builder model(String model){
            this.model = model;
            return this;
        }

        public Car build(){
            return new Car(this);
        }
    }
}

@SuperBuilder用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值