Serializable for Java serialization: serializable for serialization
Java serialization process is as follows:
The deserialization process of Java is as follows:
Note: not all classes need to be serialized for two main reasons:
1) security issues. Some Classes in Java are sensitive. The object data of this class cannot be made public, and the serialized object data can be easily cracked, so the data security cannot be guaranteed, therefore, this type of object will not be serialized.
2) resource problems. You can use serialized byte streams to create objects, which are unrestricted during creation. Sometimes too many objects are created, which may cause great resource problems. Therefore, such objects are not suitable for serialization.
Serializable
Serializable is a serialization interface provided by Java. It is an empty interface that provides standard serialization and deserialization operations for objects.
Serialization process:
1 Person p = new Person("name","id");2 File file = new File("cache.txt");3 FileOutputStream output = new FileOutputStream(file);4 ObjectOutputStream objectOutputStream = new ObjectOutputStream(output);5 objectOutputStream.writeObject(p);6 output.close();7 objectOutputStream.close();
Deserialization process:
1 File file = new File("cache.txt");2 FileInputStream input= new FileInputStream(file);3 ObjectInputStream objectInputStream = new ObjectInputStream(input);4 Person p = (Person)objectInputStream.readObject();5 System.out.println(p.getName()+"---"+p.getId());6 input.close();7 objectInputStream.close();
- Class member to be serialized
During Object serialization, not all Members must be converted to a binary byte sequence, because some unnecessary members do not need to be serialized to save storage or transmission space and improve serialization efficiency. Including:
-
- Static variable. Static variables are attributes of a class and do not belong to a specific instance. Therefore, they do not need to be serialized during serialization. During deserialization, you can directly obtain static member references of the class.
- Method. Methods are just a series of operation sets. methods do not depend on objects, but are operated differently. During deserialization, method information can be directly obtained from classes.
- Serialization of inheritance relationships
- When the parent class implements Serializable, The subclass is serialized, and the parent class is also serialized.
- When the parent class does not implement Serializable, The subclass is serialized and the parent class is not serialized.
- Serialization of reference relationships
If a class that implements Serializable is serialized, its referenced classes are serialized at the same time. If the referenced class does not implement the Serializable interface, JVM will throw java. io. NotSerializableExeception.
1 class Person implements Serializable{2 private String name;3 private Tool tool = new Tool();4 }5 6 class Tool implements Serializable{7 8 }
In this case, the Person class will be serialized at the same time. If the Tool class does not implement the Serializable interface, an exception is thrown.
- Protect sensitive data:
- After a class is added with a serialization identifier, all attributes of the class object will be serialized and then stored locally or transmitted over the network. Sometimes some fields in the object are sensitive information and should not be exposed. If it is also serialized, it is easy to be cracked, resulting in security risks, such as common password fields.
- Java provides a keyword transient, that is, the instantaneous keyword. This keyword disables field serialization so that protected information is not exposed due to serialization.
- Serialization ID
- Imagine the scenario where the two ends transmit serialized objects over the network. For some reason, the versions of the classes used at the two ends are different. Assume that the class of the receiver is deleted from several fields. When an object's serialized byte stream is sent to the receiver, the class of the receiver cannot be parsed because several fields are missing.
- Java requires that all classes that implement the serialization interface must declare a serialVersionUID static attribute. If this attribute is not present, JVM automatically declares this attribute, assign a value to this attribute (different values are assigned when the class changes ). The value of this attribute is unique and used to identify different serialization classes. Java deserializes a class only when its serialization identifier is identical. This is the role of the serialization identifier.
- For the preceding scenario, if the serialVersionUID is not manually declared, the JVM will assign different values to the serialVersionUID in the class used by the sender and receiver, and the deserialization will fail. When you manually assign a value to the serialVersionUID, The deserialization is successful even if the class segment is changed.
- Custom serialization Policy
- Custom serialization Policy
Java provides an effective mechanism to allow custom methods for processing during serialization and deserialization. After both parties have agreed on a serialization policy, you only need to add a set of methods to the serialization class to be transmitted to implement this policy, during serialization, these specified methods are automatically called for serialization and deserialization. The method is as follows:
1) private void writeObject (ObjectOutputSteam out) throws IOException
There is an important code inside the method: out. defaultWriteObject () // write the object data to the output stream by default.
2) private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException
Similarly, this method has similar code: in. defaultReadObject (); // restores an object from the input stream by default.
These two methods are used to write specific objects to the output stream and restore specific objects from the input stream. With these two methods, you can implement custom serialization. When the above two methods are written in the class implementing the Serializable interface, serialization or deserialization of the class will call these two methods through reflection to implement custom serialization.
-
- Limit the number of serialized objects
Let's look at the following Singleton mode:
1 public class Singleton implements Serializable { 2 3 private volatile static Singleton mInstance; 4 private Singleton() { 5 } 6 7 public static Singleton getInstance() { 8 if (mInstance == null) { 9 synchronized (Singleton.class) {10 if (mInstance == null) {11 mInstance = new Singleton();12 }13 }14 }15 return mInstance;16 }17 }
In this case, the singleton mode fails when the instance is obtained through deserialization. How can we solve this problem?
Java has a mechanism that allows us to write or read specified instances as needed during serialization and deserialization. To use this mechanism, you need to add two methods to the class implementing the Serializable interface:
- Private Object readResolve () // if the user adds this method to the serialization class, the Object returned by this method is used as the deserialization Object during deserialization.
- Private Object writeReplace () // if the user adds this method to the serialization class, the Object returned by this class will be serialized during serialization.
Let's look at the singleton mode with this mechanism:
1 1 public class Singleton implements Serializable { 2 2 3 3 private volatile static Singleton mInstance; 4 4 private Singleton() { 5 5 } 6 6 7 7 public static Singleton getInstance() { 8 8 if (mInstance == null) { 9 9 synchronized (Singleton.class) {10 10 if (mInstance == null) {11 11 mInstance = new Singleton();12 12 }13 13 }14 14 }15 15 return mInstance;16 16 }17 17 18 18 private Object readResolve() {19 19 return getInstance();20 20 }21 21 22 22 private Object writeReplace() {23 23 return getInstance();24 24 }25 25 }
At this time, the same object is obtained through deserialization, that is, the singleton mode is still valid!