Objenesis - 如何初始化字段

时间:2017-12-19 11:03:07

标签: java initialization objenesis

如何将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初始化这些字段?

1 个答案:

答案 0 :(得分:0)

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

你的用例是什么?