本文介绍了匿名类的NotSerializableException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于过滤项目的接口:

  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:


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.NotSerializableExceptionHow do I make the anonymous class I wrote Serializable?

解决方案

Joshua Bloch writes in his book Effective Java, 2nd Edition, Item 74:

这篇关于匿名类的NotSerializableException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 00:07