在试验和浏览序列化机制的代码时发现了一些东西:
1)如果发现对象是Externalizable,则将其强制转换为Externalizable,并在其上调用相应的方法;而对于可序列化对象,它会反射性地检查它是否具有 readObject/writeObject。所以也许这会让它稍微慢一点,
2)Externalizable写入的数据量比readObject/writeObject的Serializable略少(我在写B的对象时发现以下代码有1个字节的差异)。
对于外部化:
static class A implements Externalizable
{
@Override
public void writeExternal(ObjectOutput out) throws IOException
{
System.out.println("A write called");
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
System.out.println("A read called");
}
}
static class B extends A implements Externalizable
{
@Override
public void writeExternal(ObjectOutput out) throws IOException
{
super.writeExternal(out);
System.out.println("B write called");
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
super.readExternal(in);
System.out.println("B read called");
}
}
对于可序列化:
static class A implements Serializable
{
private void writeObject(ObjectOutputStream out) throws IOException
{
System.out.println("A write called");
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
System.out.println("A read called");
}
}
static class B extends A implements Serializable
{
private void writeObject(ObjectOutputStream out) throws IOException
{
System.out.println("B write called");
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
System.out.println("B read called");
}
}