我有一个仅包含静态方法的实用程序类
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:DataClass 的可序列化类中的非 transient 非序列化实例字段
。
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 手动添加每行,而不是创建匿名子类。
关于java - 具有实用程序静态方法的类给出非 transient 不可序列化实例字段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60768675/