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
.