We have seen that serialization in java is automatic and all we need is implementing Serializable interface. The implementation is present in the ObjectInputStream and ObjectOutputStream classes. But what if we
import java.io.*; public class SerializationExample { public static void main(String[] args) { // 创建一个对象 Person person = new Person("John Doe", 30); // 序列化对象 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) { oos.writeObject(person)...
In this example,person1andperson2share the sameAddressobject. Whenperson1andperson2are serialized, theAddressobject is serialized only once. During deserialization, theAddressobject is restored only once and shared byperson1andperson2. This is because Java serialization maintains the object graph, pres...
Serialization with Inheritance relationship If a superclass is Serializable, then according to normal Java interface rules, all subclasses of that class automatically implement Serializable implicitly. In other words, a subclass of a class marked Serializable passes the IS-A test for Serializable, and ...
package de.vogella.java.serilization; import java.io.Serializable; public class Person implements Serializable { private String firstName; private String lastName; // stupid example for transient transient private Thread myThread; public Person(String firstName, String lastName) { this.firstName = ...
ExampleConsider the case of an original class and two instances in a linked list: class List implements java.io.Serializable { int value; List next; public static void main(String[] args) { try { List list1 = new List(); List list2 = new List(); list1.value = 17; list1.next =...
package java.io; public class ObjectStreamField implements Comparable { public ObjectStreamField(String fieldName, Class fieldType); public ObjectStreamField(String fieldName, Class fieldType, boolean unshared); public String getName(); public Class getType(); public String getTypeString(); public ...
第一个示例简单演示了如何序列化和反序列化数据对象。 它需要名为 Person 的类,如下所示。 C#复制 usingSystem;usingSystem.Collections.Generic;usingSystem.Web.UI;usingSystem.Web.Script.Serialization;namespaceExampleApplication{publicpartialclass_Default:Page{protectedvoidPage_Load(objectsender, EventArgs e){var...
Always include it as a field, for example: “private static final long serialVersionUID = 7526472295622776147L; ” include this field even in the first version of the class, as a reminder of its importance. Do not change the value of this field in future versions, unless you are knowingly...
A number of popular object-oriented programming languages provide either native support for serialization or have libraries that add non-native capabilities for serialization to their feature set. Java, .NET, C++, Node.js, Python, and Go, for example, all either have native serialization support ...