On serialization

serialize

The premise of reading and writing an object is that the object of this type is serializable
Serialization of objects is simply to convert objects directly into binary data streams
The deserialization of an object converts a binary data stream into an object
Serialization and deserialization of objects are implemented through the JVM. Only declarations are made in programming. The goal of serialization is to save objects to the JVM
Disc or allows direct transmission in the network
Programming application
1. It depends on the serializable interface for declaration. If special operations are required, the Externalizable interface can be implemented. Serializable interface
It belongs to flag interface [identification interface], which only serves as a description, and there is no method to be implemented
Redefine the Account class
2. You can read and write objects directly through the methods provided by ObjectInputStream and ObjectOutputStream
Persisting an object to a file through serialization
Reads an object from a file into memory by deserialization

1 public interface Serializable { }
public class Account implements Serializable{
private Long id;//Account number
private String username;//title of account
private String password;//Account password
private Double balance;//balance
Account account = new Account();
account.setId(99L);
account.setUsername("Zhao xiaopang");
account.setPassword("123456");
account.setBalance(1234.56);
// Store objects in files
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new
FileOutputStream("out/account.data")));
oos.writeObject(account);
oos.close();
System.out.println("Serialization of storage objects completed");

1. Interface problem

Objects that need to be read and written through the object stream must implement the serialization interface, otherwise NotSerializableException

 public class Account implements Serializable

Potential requirement: requires that the class must be constructed by a parameterless constructor, because the parameterless constructor needs to be called to build the object during deserialization. Otherwise, Exception
in thread "main" java.io.InvalidClassException: com.yan.test01.Account; no valid
constructor
Best software practice: if you need to define a constructor, it is generally recommended to provide a parameterless constructor
If you need to serialize an object of a certain type, it is required that all properties of the type also support serialization. Otherwise, similar problems occur
Exception in thread “main” java.io.NotSerializableException: com.yan.test03.Role newspaper
wrong

ublic class Account implements Serializable {
private static final long serialVersionUID = 4093553615911145103L;
private Long id;// Account number
private String username;// title of account
private transient String password;// Account password
private Role role;
private Double balance;// balance

2. Special interface

The Serializable interface belongs to the identification interface. There is no method to be implemented. All serialization and deserialization operations are the responsibility of the virtual machine
realization.
The Externalizable interface definition can support the detailed operation of user-defined serialization, which is generally not used unless required by special requirements
Externalizable interface, because there is no need to customize it
Special application scenarios
A property of a type is not serializable. For example, the object contains properties of resource types such as InputStream/OutputStream,
Not only can it not be serialized, but resources should be released before serialization, and resource connections should be recreated during deserialization

Special application scenarios

A property of a type is not serializable. For example, the object contains properties of resource types such as InputStream/OutputStream,
Not only can it not be serialized, but resources should be released before serialization, and resource connections should be recreated during deserialization..

ublic class Account implements Externalizable{
private Long id;
private String username;
private transient String password;//It can be serialized, but it is not serialized according to business requirements
private InputStream is; //Cannot serialize
public void writeExternal(ObjectOutput out) throws IOException {
is.close(); //Turn off resource links for specific attributes
//To serialize an object is to write the data to be written out into the out object
out.writeLong(this.id);
out.writeUTF(this.username);
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
this.is=new FileInputStream("photo.jpg");
//To deserialize an object is to read data from an in object without creating a new object. Pay attention to the reading and writing order
 Must be consistent, otherwise an error will occur
this.id=in.readLong();
this.username=in.readUTF();
}
}

3. Type conversion

The Object obtained through deserialization is of Object type. If you call a special method in the Object, you must narrow it first

4. Serial number problem

In Eclipse, there will be such a warning message for the class definition that implements the serialization interface, requiring a serial number
serialiVersionUID. This is not an error message
In Eclipse, you can click the yellow exclamation mark with the mouse, a menu will pop up, and then select Add generated serial version ID
Automatically generate a serial version number that will never be repeated
The serial version number does not need to be added. This serial version number is a simple way to quickly identify types in serialization and deserialization operations
Law.
When the reverse sequence is executed, the class definition is modified and the toString method is added. An error is reported when reading the object because the system finds the modification of the class. system
The system identifies the class definition through the hash value of the class definition. If the class definition is modified, the hash value corresponding to the type will change, so it is reported
wrong. If you customize the serial version number, you can identify the type through this serial version number, which can improve efficiency and will not use the class again
Type of hash code for type identification. Therefore, no error will be reported after modifying the class and adding the method

5. Special keywords

Generally, serialization should not be carried out for sensitive data, such as the password attribute of the current account. For properties that do not require serialization
You can add a keyword transient to indicate that the attribute does not participate in serialization and deserialization operations
When reading data using readObject deserialization, you will find

6. End of flow

The end of reading the file can be judged by EOFException exception
Read all objects stored in a file
Problems in processing additional files

/ Store objects in files
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new
FileOutputStream("out/account.data",true)));//true indicates to append the file
oos.writeObject(account);
oos.close();

There will be no problem writing data, but there will be an Exception in thread "main" when reading data
java.io.StreamCorruptedException: invalid type code: AC
Solution: if you need to add object data, do not use true in FileOutputStream to append, but read all the data first
Object data, and then write out the override again

Object[] arr=new Object[100];
int counter=0;
File ff=new File("out/account.data");
if(ff.exists()){
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(ff));
while(true){
try{
Object tmp=ois.readObject();
acc[counter++]=tmp;
} catch(EOFException e){
break;
}
}
ois.close();
}
//Append new data
Account newAccount=new Account();
newAccount.setId(50L);
newAccount.setUsername("Chinese side"); ......
arr[counter++]=newAccount;
//Uniformly write out all objects in the array to the file

Serialization summary

java serialization is to convert an object into a binary byte array, and pass the pair by saving or transferring these arrays
The purpose of storing or persisting objects. Serialization requires that the class must implement the corresponding sequence interface, two serialization interfaces
Serializable [identification interface] and Externalizable [user defined method implements attribute serialization]. Deserialization is to
The process of converting a binary array into an object. When performing deserialization, there must be an original class definition to restore the object.
When the parent class implements the Serializable interface, all subclasses can be serialized; The subclass implements the Serializable interface, and the parent class does not
If there is an implementation, the attributes in the parent class cannot be serialized and data will be lost
If the Serializable interface is implemented and the class contains a property of reference type, the property must be Serializable, otherwise an error will be reported. sure
Customized serialization through Externalizable interface
If serialVersionUID is modified during deserialization, deserialization fails
Using serialization mechanism in Java environment and supported by JVM are very good, but other serialization machines can be used in multilingual environment
System, such as xml, json, etc
serialVersionUID is used to ensure compatibility issues between class serialization and deserialization. The compiler recommends two methods. One is to generate the default
The other is to generate a 64 hash field according to the class name, interface name, member method and attribute
Object cloning
Define a clone method in the Object class
The native method is used to declare a code implemented in a non java language for java programs to call. Because java language programs run on the JVM,
If you want to access and compare the underlying methods related to the operating system, there is no way. You can only realize it by comparing the language close to the system
Such as C/C + +.
There are two different cloning methods in Java: shallow clone and deep clone. Shallow cloning does not support reference type members
The copy of variables is only the address of the clone; Deep cloning supports the replication of reference type member variables
Shallow cloning
1. The copied class needs to implement the clonable interface, which is also a flag interface and does not contain any methods
2. In the current class, override the definition of clone method and set the access qualifier to public. The specific implementation calls super Clone implementation

ObjectOutputStream ois=new ObjectOutputStream(new
FileOutputStream("out/account.data")); //No true indicates overwrite
for(int i=0;i<arr.length;i++){
ois.writeObject(arr[i]);
}
ois.close();

Keywords: Java Back-end

Added by Ryan0r on Fri, 28 Jan 2022 00:31:36 +0200