匿名类上的 NotSerializableException [英] NotSerializableException on anonymous class
问题描述
我有一个过滤项目的界面:
I have an interface for filtering items:
public interface KeyValFilter extends Serializable {
public static final long serialVersionUID = 7069537470113689475L;
public boolean acceptKey(String iKey, Iterable<String> iValues);
public boolean acceptValue(String iKey, String value);
}
和一个包含 KeyValFilter
类型成员的类.
and a class containing a member of type KeyValFilter
.
public class KeyValFilterCollector extends KeyValCollectorSkeleton {
private static final long serialVersionUID = -3364382369044221888L;
KeyValFilter filter;
public KeyValFilterCollector(KeyValFilter filter) {
this.filter=filter;
}
}
当我尝试使用实现 KeyValFilter
的匿名类启动 KeyValFilterCollector
时:
When I try to initiate the KeyValFilterCollector
with an anonymous class implementing KeyValFilter
:
new KeyValFilterCollector(new KeyValFilter() {
private static final long serialVersionUID = 7069537470113689475L;
public boolean acceptKey(String iKey, Iterable<String> iValues) {
for (String value : iValues) {
if (value.startsWith("1:"))
return true;
}
return false;
}
public boolean acceptValue(String iKey, String value) {
return value.startsWith("0:");
}
});
我收到一个异常:线程main"java.io.NotSerializableException 中的异常
.
如何让我写的匿名类可以Serializable?
How do I make the anonymous class I wrote Serializable?
推荐答案
Joshua Bloch 在他的书中写道 EffectiveJava,第 2 版,第 74 项:
Joshua Bloch writes in his book Effective Java, 2nd Edition, Item 74:
内部类不应实现Serializable
.它们使用编译器生成的合成字段来存储对封闭实例的引用,并存储来自封闭作用域的局部变量的值.这些字段如何对应于类定义是未指定的,匿名类和本地类的名称也是如此.因此,内部类的默认序列化形式是不明确的.但是,静态成员类可以实现Serializable
.
Inner classes should not implement
Serializable
. They use compiler-generated synthetic fields to store references to enclosing instances and to store values of local variables from enclosing scopes. How these fields correspond to the class definition is unspecified, as are the names of anonymous and local classes. Therefore, the default serialized form of an inner class is illdefined. A static member class can, however, implementSerializable
.
这篇关于匿名类上的 NotSerializableException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!