[英]Class with utility static method gives Non-transient non-serializable instance field error
我有一個只有靜態方法的實用程序類
public final class ABC {
/**
* private constructor to prevent from object creation
*/
private ABC() {
}
private static Map<String, String> buildInfo(@NonNull final X x) {
final DataClass dataClass = x.getData();
/**
Some manipulation
**/
return info;
}
}
X 類有一個數據類
class X {
DataClass dataClass;
...
};
class DataClass {
...
Optional<String> abc;
...
}
這段代碼給出了“FindBugs 報告警告”。 SE_BAD_FIELD: Non-transient non-Serialization instance field in serializable class
。
This Serializable class defines a non-primitive instance field which is neither transient, Serializable, or java.lang.Object, and does not appear to implement the Externalizable interface or the readObject() and writeObject() methods. Objects of this class will not be deserialized correctly if a non-Serializable object is stored in this field.
為什么它在實用程序方法中給出錯誤,我不想讓事情可序列化?
那是因為我要回來了
Map<String, Integer> info = new HashMap<String, Integer>() {{
put(Constants.ID_KEY, dataClass.getId());
put(Constants.NAME_KEY, dataClass.getName());
}};
創建匿名類。
創建一個類,它是 HashMap 的子類,其中 HashMap 是可序列化的,而這個新的子類是不可序列化的。
基本上只使用 Immutable Map Builder 或 HashMap 手動添加每一行而不是創建匿名子類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.