Java serialization provides the following types of serialization: 1. Basic data type serialization; 2. Object serialization, which requires the class to implement the java.io.Serializable interface; 3. Externalization and deserialization, which requires the object to implement java .io.Externalizable interface. In actual combat, object information can be directly stored and read.
Types of Java serialization
Java serialization is a method of saving the state of an object to persistent storage or transmitting it over the network the process of. Java provides the following types of serialization:
1. Basic data type serialization
Basic data types (such as int, long, double) can be directly serialized .
// 基本数据类型序列化 int num = 100; OutputStream out = new FileOutputStream("num.ser"); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(num); oos.close();
2. Object serialization
To serialize objects, the class needs to implement the java.io.Serializable
interface.
// 对象序列化 class Person implements Serializable { private String name; private int age; // ... } Person person = new Person(); OutputStream out = new FileOutputStream("person.ser"); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(person); oos.close();
3. Externalization and deserialization
Externalization allows customization of the serialization and deserialization process. The object needs to implement the java.io.Externalizable
interface.
// 外部化 public void writeExternal(ObjectOutput out) { out.writeObject(name); out.writeInt(age); } // 反序列化 public void readExternal(ObjectInput in) { this.name = (String) in.readObject(); this.age = in.readInt(); }
Practical case
Case: Storing and reading user information
// 存储用户信息 UserInfo user = new UserInfo(); OutputStream out = new FileOutputStream("user.ser"); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(user); oos.close(); // 读取用户信息 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.ser")); UserInfo user2 = (UserInfo) ois.readObject(); ois.close();
The above is the detailed content of What are the types of java serialization and deserialization?. For more information, please follow other related articles on the PHP Chinese website!