How to make Objenesis initialize field as a normal constructor call?
Here is my code:
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));
}
and output is:
{"a":3,"b":"4","c":{}}
{"a":0,"b":null,"c":null}
{"a":0,"b":null,"c":null}
So in second and third output, there are no default values being initialized, giving me null pointer exceptions on field c. Also, String and integer fields are not initialized to their default values.
How to make Objenesis init these fields?
The purpose of Objenesis is precisely not to call any constructor or initialize any fields. To create mocks and proxies.
What is your use-case?