匿名类的NotSerializableException [英] NotSerializableException on anonymous class
问题描述
我有一个用于过滤项目的接口:
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类型成员的类。
public class KeyValFilterCollector extends KeyValCollectorSkeleton {
/ **
*
* /
private static final long serialVersionUID = -3364382369044221888L;
KeyValFilter过滤器;
public KeyValFilterCollector(KeyValFilter filter){
this.filter = filter;
}
当我尝试使用实现KeyValFilter的匿名类来启动KeyValFilterCollector时: (KeyValFilter()){
private static final long serialVersionUID = 7069537470113689475L;
public boolean acceptKey() (字符串值:iValues){
if(value.startsWith(1:))
return true;
}
返回false;
}
public boolean acceptValue(String iKey,String value){
返回value.startsWith(0:);
}
});
我得到一个异常:线程main中的异常java.io.NotSerializableException
我写了Serializable的匿名类吗?
www.oracle.com/technetwork/java/effectivejava-136174.html\"> Effective Java,2nd Edition ,Item 74:
内部类不应该实现
Serializable
。它们使用编译器生成的合成字段来存储对封闭实例的引用,并存储来自封闭范围的局部变量值。未指定这些字段如何与类定义相对应,匿名类和本地类的名称也是如此。因此,内部类的默认序列化形式不确定。但是,静态成员类可以实现Serializable
。
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);
}
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;
}
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:");
}
});
I get an exception: Exception in thread "main" java.io.NotSerializableException How do I make the anonymous class I wrote Serializable?
Joshua Bloch writes in his book Effective Java, 2nd Edition, Item 74:
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屋!