Java serialization is what? You know when you need to be serialized?
What is java serialization? You need to serialize under what circumstances?
Serialization: process converts Java objects into a stream of bytes.
Deserialization: byte transfer process into Java objects.
When a Java object need to be transmitted over a network or the persistent storage into a file, it is necessary to process Java object serialization.
Realized sequence: class implements Serializable interface, this interface does not need to implement the method of. Implement Serializable to tell jvm objects of this class can be serialized.
Precautions:
A class can be serialized, the subclasses may be serialized
Declared as a member variable static and transient and can not be serialized. static member variables are described class-level attributes, transient temporary data representation
Deserializing serialized objects sequentially read consistency
Specific use
package constxiong.interview; import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable; /** * 测试序列化,反序列化 * @author ConstXiong * @date 2019-06-17 09:31:22 */public class TestSerializable implements Serializable { private static final long serialVersionUID = 5887391604554532906L; private int id; private String name; public TestSerializable(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "TestSerializable [id=" + id + ", name=" + name + "]"; } @SuppressWarnings("resource") public static void main(String[] args) throws IOException, ClassNotFoundException { //序列化 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("TestSerializable.obj")); oos.writeObject("测试序列化"); oos.writeObject(618); TestSerializable test = new TestSerializable(1, "ConstXiong"); oos.writeObject(test); //反序列化 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("TestSerializable.obj")); System.out.println((String)ois.readObject()); System.out.println((Integer)ois.readObject()); System.out.println((TestSerializable)ois.readObject()); } }
Print Results:
The test sequence of 618 TestSerializable [=. 1 ID, name = ConstXiong]
Like this article, you can point to the author likes to point at attention, will share Java-related articles every day!
Remember to focus on me oh, will occasionally presented benefits, including consolidation of interview questions, learning materials, source code, etc. ~ ~