简体   繁体   中英

Non-static inner classes like this can only by instantiated using default, no-argument constructor error when deserialize

I am trying to serialize and deserialize my object but I got an error during deserialization:

Cannot construct an instance of 'MyObject' (although at least one Creator exists): 
non-static inner classes like this can only be instantiated using a default, no-argument constructor.

I had constructor for class MyObject with 2 parameters but I changed it to default constructor, but it still throw the same error.

This is my code:

@Test
public void serializeAndDeserializeTest() throws JsonProcessingException {
    var list = new MyObject[2];
    var t1 = new MyObject();
    t1.value1 = TestEnum.VALUE5.numVal;
    t1.value2 = "A";
    var t2 = new MyObject();
    t2.value1 = TestEnum.VALUE1.numVal;
    t2.value2 = "B";
    list[0] = t1;
    list[1] = t2;
    var mapper = new ObjectMapper();
    var json = mapper.writeValueAsString(list);
    MyObject[] output = mapper.readValue(json, MyObject[].class);
}

public class MyObject
{
    public int value1;
    public String value2;
}

public enum TestEnum
{
    VALUE1(1),
    VALUE3(3),
    VALUE5(5);

    public int numVal;

    TestEnum(int numVal) {
        this.numVal = numVal;
    }
}

I also tried to create a private default constructor but it doesn't work.

In order to fix this, make the MyObject inner class static:

public static class MyObject {
    public int value1;
    public String value2;
}

Without the static keyword, the inner class needs an instance of the encompassing outer class in order to exist. This is what causes the exception.

For the enum that is not the case because inner enums are implicitly static, see the Java Language Specification, chapter 8.9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM