Objenesis - 如何初始化字段

Objenesis - how to initialize fields

如何使 Objenesis 初始化字段作为普通构造函数调用?

这是我的代码:

public static class MakeThis implements Serializable{
        private int a = 3;
        private String b = "4";
        private HashMap<String, String> c = new HashMap<>();

        public int getA() {
            return a;
        }

        public void setA(int a) {
            this.a = a;
        }

        public String getB() {
            return b;
        }

        public void setB(String b) {
            this.b = b;
        }

        public HashMap<String, String> getC() {
            return c;
        }

        public void setC(HashMap<String, String> c) {
            this.c = c;
        }
    }

    void serialize() throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        MakeThis m = new MakeThis();
        System.out.println(om.writeValueAsString(m));
        MakeThis m2 = new ObjenesisStd().newInstance(MakeThis.class);
        System.out.println(om.writeValueAsString(m2));
        MakeThis m3 = new ObjenesisSerializer().newInstance(MakeThis.class);
        System.out.println(om.writeValueAsString(m3));
    }

输出为:

{"a":3,"b":"4","c":{}}
{"a":0,"b":null,"c":null}
{"a":0,"b":null,"c":null}

所以在第二个和第三个输出中,没有初始化默认值,在字段 c 上出现空指针异常。此外,字符串和整数字段未初始化为其默认值。

如何让 Objenesis 初始化这些字段?

Objenesis的目的恰恰是不调用任何构造函数或初始化任何字段。创建模拟和代理。

你的用例是什么?