What is a good way to make a class unserializable?
coding-style, java, serialization
Solution
Quoting from this JavaRevisited article (see #8):
To avoid java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.
So you just need to paste this into your class:
private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException {
throw new java.io.NotSerializableException( getClass().getName() );
}
private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException {
throw new java.io.NotSerializableException( getClass().getName() );
}
Problem
Java contains a lot of classes (like in Swing) which implement the dreaded and error prone interface `Serializable`. If you implement, say, a new `TableModel` by extending `AbstractTableModel`, the new model must be serializable but what if it contains internal data types which aren't serializable and which don't have to be since you don't plan to use this feature anyway? In such a case, tools like Sonar go crazy. The either complain that "Class `Foo` defines non-transient non-serializable instance field `bar`". So I make that field `transient` just to get "The field `Foo.bar` is transient but isn't set by deserialization" Is it possible to say "No, this class isn't serializable, and I don't want it to be" in such a way that you don't get any errors in tools like Sonar?