Java basics - the use of serialization framework for data serialization

Why serialize?

Nowadays, during the development process, we often encounter multiple processes and multiple services that need to interact, or services in different languages ​​need to interact. At this time, we generally choose to use a fixed protocol to transmit data, but in many languages, such as Java, In the JVM language, the transmitted data is a unique class object, and the class object is only valid in the current JVM. When passing it to other JVMs or to other languages, the class object cannot be directly identified. Then, we What should I do if I need to interact with multiple services or in different languages? At this time, we need to transmit a fixed data format through a fixed protocol, and this data transmission protocol is called serialization, and the framework component that defines the behavior of transmitting data is also called a serialization component (framework).
The serialization framework will contain two operations, one is to convert an object or data structure into a specific format (transfer data protocol), which we call serialization; the other is the process of converting a specific format into an object or data structure, We call it deserialization.

The purpose of serialization

  • Enables data to be transmitted over a network or stored in memory or files.
  • Allow data to exist independently of the application.

Serialization usage scenarios

Interaction between different services, services can be in the same language or in different languages.

Java language built-in serialization

The implementation of serialization can be divided into text serialization, language built-in serialization and cross-language serialization. This article mainly talks about the Java language built-in serialization.
Each language basically has an implemented serialization framework. This serialization method is called language built-in serialization. Its advantage is that the language provides a serialization framework (serialization protocol, serialization and deserialization operations). Easy to use, the disadvantage is that interactive applications must be in the same language.
The following will describe the use of Java's built-in serialization framework. The Java serialization protocol is a byte sequence (implemented by jvm).

The core used by the serialization framework
  • Serialization interface (Serializable and Externalizable)

    The class object that needs to be serialized needs to inherit this interface. Only the class object defined by the current interface modification can transmit the object in the specified way.

  • serializationid-serialVersionUID

    Check whether the versions of the double-ended process (javaBean) used for transmission/reading are consistent to prevent us from serialization failure due to inconsistent versions.
    The compiler provides two ways to serialize IDs, one is to generate the default versionID, which has a value of 1L, and the other is to generate a 64-bit hash field based on the class name, interface name, member method and attribute, etc. , as long as our class name, method name, variable is modified, or there are spaces, comments, newlines and other operations, the calculated hash field will be different. Of course, we need to pay attention here. Try to re-run it every time we have the above operations. Generate serialVerionUID once (the compiler will not automatically modify it for you).
    The default fixed value of 1L and the 64-bit hash value do not need to be calculated by yourself. For classes that inherit the serialization interface, if there is no serialization id field, a yellow wavy line will be displayed under the class name. Place the mouse on the class name and select the desired method to automatically add the serialized id field (if there is any change, delete it and then add it according to the prompts).

  • Object serialization and data writing operations (output stream java.io.ObjectOutputStream)

    Used to perform serialization operations and write the serialized data to a file or transmit it.

  • Data reading and object deserialization operations (input stream java.io.ObjectInputStream)

    Used to perform deserialization operations to deserialize files or data received from the network into objects.

Case 1 - Basic serialization and deserialization Serializable

The following takes the serialized object stored in the file, reading the file and then using the object as an example to explain the use of the serialization framework. This use is the same as serializing the data before transmitting it, because it is required for both data transmission and file access. Input and output streams, only the parameters for obtaining the input and output streams are inconsistent.

Person class implementation
public class Person implements Serializable {
    
    
	//64位哈希序列化ID
	private static final long serialVersionUID = 8247451571741032209L;
	private String name;
	private int age;
	private transient boolean isMan; // true=男,false=女

	public Person(String name, int age, boolean isMan) {
    
    
		this.name = name;
		this.age = age;
		this.isMan = isMan;
	}

	public String getName() {
    
    
		return name;
	}

	public void setName(String name) {
    
    
		this.name = name;
	}

	public int getAge() {
    
    
		return age;
	}

	public void setAge(int age) {
    
    
		this.age = age;
	}

	public boolean isMan() {
    
    
		return isMan;
	}

	public void setMan(boolean isMan) {
    
    
		this.isMan = isMan;
	}
	
	/*此方法只是用于打印,与序列化无关*/
    public String toString() {
    
    
        return "Person{" + "name=" + name  + ",age = " + age+",isMan = " + isMan + "}";
    }

}
Serialization operation
public static void writeObject() {
    
    
		try {
    
    
			// 0. 创建一个ObjectOutputStream输出流
			ObjectOutputStream oos = new ObjectOutputStream(
					new FileOutputStream("E:/object.txt"));
			// 1. 将对象序列化到文件s
			Person person = new Person("lilu", 18, true);
			oos.writeObject(person);
			System.out.println("Person对象已写入object.txt文件");
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
Deserialization operation
public static void readObject() {
    
    
		try {
    
    
			// 0. 创建ObjectInputStream
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
					"E:/object.txt"));
			Person person1 = (Person) ois.readObject();
			System.out.println("读取到的Person对象数据如下:");
			System.out.println(person1);
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
main function call
public static void main(String[] args) {
    
    
		writeObject();
		readObject();
	}
operation result

Insert image description here

Summary of Java serialization usage
  • Java serialization is only for the transfer of object attributes (object class name, variable type, variable data), and methods have nothing to do with the serialization process.
  • A certain member variable in the class does not need to be serialized. Use transient to declare the field.
  • Class static variables (variables modified by static) will not be serialized.
  • Members are reference serializations, and the class corresponding to this reference type must also be serializable.
  • Serialization is transitive - when a parent class implements serialization, the subclass will automatically implement serialization without explicitly implementing the serialization interface. In turn, the subclass implements serialization, and the parent class does not implement serialization. will fail. If the same object is serialized multiple times, the same object will not be serialized multiple times. Instead, no matter how many serialization operations are performed, only the same object will be obtained.

Expand

  • Custom serialization, override writeObject and readObject
  • Inherit interfaceExternalizable
  • Detailed explanation of the source code of the serialization framework
  • Implementation of cross-language serialization

Reference link

Java serialization, just read this article!
Detailed explanation of JAVA serialization
Newbie tutorial-Java serialization

Guess you like

Origin blog.csdn.net/li1500742101/article/details/105509360