![](/img/trans.png)
[英]Why do I get the “non-static variable this cannot be referenced from a static context” error only when I have inner classes?
[英]Non-static inner classes like this can only by instantiated using default, no-argument constructor error when deserialize
我正在嘗試序列化和反序列化我的對象,但在反序列化過程中出現錯誤:
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.
我有帶有 2 個參數的類 MyObject 的構造函數,但我將它更改為默認構造函數,但它仍然拋出相同的錯誤。
這是我的代碼:
@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;
}
}
我還嘗試創建一個私有默認構造函數,但它不起作用。
為了解決這個問題,將MyObject
內部類設為靜態:
public static class MyObject {
public int value1;
public String value2;
}
如果沒有 static 關鍵字,內部類需要包含外部類的實例才能存在。 這就是導致異常的原因。
對於不是這種情況的enum
,因為內部枚舉是隱式靜態的,請參閱Java Language Specification,第 8.9 章
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.