java对象序列化readObject / defaultReadObject
ObjectInputStream
类中的readObject
和defaultReadObject
什么区别? 我似乎无法找到有关差异的非常多的信息。
defaultReadObject()
调用默认的反序列化机制,并在Serializable
类上定义readObject()
方法时使用。 换句话说,当您具有自定义反序列化逻辑时,您仍然可以返回到默认序列化,这将反序列化非静态非瞬态字段。 例如:
public class SomeClass implements Serializable { private String fld1; private int fld2; private transient String fld3; private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); //fills fld1 and fld2; fld3 = Configuration.getFooConfigValue(); } ]
另一方面,当您从反序列化对象外部创建ObjectInputStream
并且想要读取先前序列化的对象时,将使用readObject()
:
ObojectInputStream stream = new ObjectInputStream(aStreamWithASerializedObject); Object foo = (Foo) stream.readObject();