上一篇讲到Serializable实现类定义私有的writeObject和readObject方法就能实现自定义序列化,但由于这两个方法是私有的,那就意味着子类序列化方法既不会继承,也不会覆盖。也就是说,对于整个继承层次中的类,都会从父类至子类依次调用序列化操作。但是有的时候,我们希望子类复用父类的序列化实现,又或者子类重写父类的序列化实现,那么这时候我们就需要用到java.io.Externalizable接口了。
public interface Externalizable extends java.io.Serializable { void writeExternal(ObjectOutput out) throws IOException; void readExternal(ObjectInput in) throws IOException, ClassNotFoundException; }
其中定义了两个public的方法,子类可以复用了。
private void writeOrdinaryObject(Object obj, ObjectStreamClass desc, boolean unshared) throws IOException { if (extendedDebugInfo) { debugInfoStack.push( (depth == 1 ? "root " : "") + "object (class \"" + obj.getClass().getName() + "\", " + obj.toString() + ")"); } try { desc.checkSerialize(); bout.writeByte(TC_OBJECT); writeClassDesc(desc, false); handles.assign(unshared ? null : obj); if (desc.isExternalizable() && !desc.isProxy()) { writeExternalData((Externalizable) obj); } else { writeSerialData(obj, desc); } } finally { if (extendedDebugInfo) { debugInfoStack.pop(); } } }
private void writeExternalData(Externalizable obj) throws IOException { PutFieldImpl oldPut = curPut; curPut = null; if (extendedDebugInfo) { debugInfoStack.push("writeExternal data"); } SerialCallbackContext oldContext = curContext; try { curContext = null; if (protocol == PROTOCOL_VERSION_1) { obj.writeExternal(this); } else { bout.setBlockDataMode(true); obj.writeExternal(this); bout.setBlockDataMode(false); bout.writeByte(TC_ENDBLOCKDATA); } } finally { curContext = oldContext; if (extendedDebugInfo) { debugInfoStack.pop(); } } curPut = oldPut; }例子和上篇大同小异不在举例了。
本文探讨了Java中使用Externalizable接口实现序列化的高级方法,通过覆盖public方法实现子类对父类序列化过程的复用或定制。

301

被折叠的 条评论
为什么被折叠?



