This article shares the serialization and deserialization of java objects for your reference. The specific content is as follows
1. What is serialization
Convert an object into a byte stream and save it, such as saving it to a file, and restoring the object later. This mechanism is called object serialization. (Additional sentence: Saving objects to permanent storage devices is called persistence)
2. How to implement serialization <br /> It is necessary to implement the Serializable interface. If a java object implements this interface, it means that the object of this class is serializable.
3. Notes on serialization
(1) When an object is serialized, it can only save non-static member variables of the object, and cannot save methods and static member variables.
(2) Object A refers to object B, object A is serialized, and B is serialized as well.
(3) If a serializable object contains a reference to an unserialized object, the entire serialization operation will fail, and a NotSerializableException will be thrown. Therefore, both the object and the reference object must implement the Serializable interface before serialization can be performed.
(4) If the use of transient, member variables or references are marked as transient, then the object can still be ordered, but it will not be serialized into the file.
4. Code
public class Person implements Serializable { private String name; private transient int age; public Person(String name, int age) { super(); this.name = name; this.age = age; } public String toString() { return this.name + "-" + this.age; } } public class SerializableClient { public static void main(String[] args) throws Exception { Person p1 = new Person("zhangsan", 5); Person p2 = new Person("lisi", 100); //Serialize FileOutputStream fos = new FileOutputStream("person.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(p1); oos.writeObject(p2); System.out.println("---------"); //Deserialize FileInputStream fis = new FileInputStream("person.txt"); ObjectInputStream ois = new ObjectInputStream(fis); for(int i = 0; i < 2; i++) { Person tempPerson = (Person)ois.readObject(); System.out.println(tempPerson); } } }
Output result:
------------
zhangsan-0
lisi-0
5. Fine-grained control serialization and deserialization
When we implement the above two private methods in the serialization or deserialization class (the method declaration must be completely consistent with the above), it allows us to control the process of serialization and deserialization in a more underlying and more inherited granular way.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.