如何使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上提供了null指针异常。另外,字符串和整数字段未针对其默认值初始化。
如何使这些字段启动?
objenesis的目的是不调用任何构造函数或初始化任何字段。创建模拟和代理。
您的用例是什么?