A:怎么会有如此奇葩的需求?。。你不知道这违反了里氏替换原则吗?(子类对象可以无条件的替换父类对象) 好吧,如果你非要这样做,给你两条建议作为参考:
- 把父类标记为final,这样就没人可以继承它了(我知道这完全不是你想要的结果…)
- 把父类或子类中的一些字段标记为transient,这样你就可以只序列化你想要的字段了。
B:你可以在子类中实现以下接口(如果类中实现了一下接口,那么在使用ObjectInput/OutputStream序列化的时候就会反射调用这些方法而不去执行默认的行为),然后都抛出一个异常,这样就可以阻止子类序列化了。
class MySubClass extends SomeSerializableSuperClass
{
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
throw new NotSerializableException(“Can not serialize this class”);
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
throw new NotSerializableException(“Can not serialize this class”);
}
private void readObjectNoData() throws ObjectStreamException; {
throw new NotSerializableException(“Can not serialize this class”);
}
}
参考:
http://howtodoinjava.com/spring/spring-core/spring-bean-life-cycle/ 倒数第二个评论部分
http://bluepopopo.iteye.com/blog/486548 有关writeObject和readObject