使用lombok进行bulider之后调取HashMap的自定义方法进行对象操作报空指针异常(pojo也适用)

概论

这主要的问题就是bulider的特性的问题,就是他只能给你搭建了一个脚手架,里面的东西其实他没动你的,你得自己去给他实体化,如果你使用了类似HashMap等集合的话,你得自己去bulid一个在那个里面作为初始化对象你才可以调取对应的对象。

@bulider的实际编译后的代码展示

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

package com.example.entity;

import java.util.HashMap;

public class R {
    private HashMap<String, Object> data;

    public boolean pushData(String key, Object val) {
        Object previousValue = this.data.put(key, val);
        return val.equals(previousValue);
    }

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

    public R(Integer code, String inf, HashMap<String, Object> data) {
        this.code = ResponseCode.SUCCESS.getCode();
        this.inf = "成功!";
        this.data = new HashMap();
        this.code = code;
        this.inf = inf;
        this.data = data;
    }

    public HashMap<String, Object> getData() {
        return this.data;
    }

    public void setData(HashMap<String, Object> data) {
        this.data = data;
    }

    protected boolean canEqual(Object other) {
        return other instanceof R;
    }


    public R() {
        this.code = ResponseCode.SUCCESS.getCode();
        this.inf = "成功!";
        this.data = new HashMap();
    }

    public String toString() {
        return "R(code=" + this.getCode() + ", inf=" + this.getInf() + ", data=" + this.getData() + ")";
    }

    public static class RBuilder {
        private Integer code;
        private String inf;
        private HashMap<String, Object> data;

        RBuilder() {
        }

        public RBuilder data(HashMap<String, Object> data) {
            this.data = data;
            return this;
        }

        public R build() {
            return new R( this.data);
        }

        public String toString() {
            return "R.RBuilder(code=" data=" + this.data + ")";
        }
    }
}

解决方法

public static void main(String[] args) {
    R k = R.builder()
            .data(new HashMap<String,Object>())
            .build();
    k.pushData("fds", "fdsf");
}

直接在builder的时候直接new一个对象作为初始化的对象就不会报空指针异常了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

堕落年代

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值