[英]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.我有带有 2 个参数的类 MyObject 的构造函数,但我将它更改为默认构造函数,但它仍然抛出相同的错误。
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:为了解决这个问题,将MyObject
内部类设为静态:
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.如果没有 static 关键字,内部类需要包含外部类的实例才能存在。 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对于不是这种情况的enum
,因为内部枚举是隐式静态的,请参阅Java Language Specification,第 8.9 章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.