使用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一个对象作为初始化的对象就不会报空指针异常了