I have a class A which implements the interface serializible. There are two sub classes B and C which extends A. I want class B not be serializible? How开发者_如何学Python can I achieve it?
Since by definition, a Java class is serializable if it implements the Serializable
interface, a serializable class cannot have a non-serializable subclass.
So one should think twice before implementing that interface on a class high up the inheritance tree or extending it in an interface. I know of a project where the top-level IIdentifiable
interface extends Serializable
, forcing all of the domain classes to be serializable. Unfortunately (for the collegue who wanted to use that feature), many of them are not serializable in practice, because:
You can prevent serialization at runtime by any of several ways:
- By adding a member variable of a type that does not implement
Serializable
(as jefflub's answer suggests), or - by implementing the method
private void writeObject(java.io.ObjectOutputStream out) throws IOException
(with that exact signature) and throwing anIOException
in that method,
any attempt to serialize the class will throw an exception.
To class B, add a non-serializable member variable:
public class B extends A
{
NoSerialize stopper = new NoSerialize();
// other instance stuff
private class NoSerialize
{
// Not sure if you'll need instance stuff here...
}
}
Trying to serialize this should throw an exception since the stopper member variable is not serializable.
I would implement the writeObject
method and have it throw an exception.
I'm not sure of the context, but you should probably take another look at your design. Following the IS-A principle of inheritance, objects of type B or C are also members of the class A and should thus be Serializable (since A is). If you are not free to redesign the object hierarchy, then some of the hacks mentioned in the other answers will work, but you should be cognizant of the fact that the design is far from ideal and take great care in the future when determining which interfaces a subclassable class should implement.
I think you can not do this, but you can use the keyword transient on some of it's properties.
精彩评论