Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Java objects often need to be transferred over the network using sockets or saved to files. Whether the Java object is a file, data, image, or other format, it can be converted to a byte[] array and stored in a file or transmitted over the network. This type of transformation is called serialization. Converting an array of Byte [] from a file or network transfer into a Java object is called deserialization.

How to use

For a Java object to be serialized, a special java.io.Serializable interface must be implemented

public interface Serializable { } 
Copy the code

The Serializable interface defines no methods and is an empty interface. Why have such an interface? Mainly because of security. The absence of this interface means that all Java objects can be serialized to disk, and then the data for all properties can be seen through deserialization. With Serializable, developers can choose which Java objects can be serialized and deserialized, increasing security.

serialization

The following example serializes a Java object and saves it to a file.

public class Person implements Serializable {

    private String name;
    private int age;
    private String hobby;

    public String getName(a) {
        return name;
    }

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

    public int getAge(a) {
        return age;
    }

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

    public String getHobby(a) {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    @Override
    public String toString(a) {
        return "Person{" +
                "name='" + name + '\' ' +
                ", age=" + age +
                ", hobby='" + hobby + '\' ' +
                '} '; }}Copy the code

To turn a Java object into a Byte [] array, use ObjectOutputStream. It is responsible for writing a Java object to a byte stream:

public class Test {

    public static void main(String[] args) throws Exception {
        Person person1 = new Person();
        person1.setAge(18);
        person1.setName("Pony");
        person1.setHobby("Painting");

        Person person2 = new Person();
        person2.setAge(50);
        person2.setName("Little army");
        person2.setHobby("Phishing");

        List<Person> list = new ArrayList<>();
        list.add(person1);
        list.add(person2);
        FileOutputStream fos = new FileOutputStream("D:\\person.txt");
        try ( ObjectOutputStream os = new ObjectOutputStream(fos)){
            os.writeObject(list);
        }
        System.out.println("Serialized successfully"); }}Copy the code

At this point, the two Person objects are serialized into D:\person.txt. Open the file, it should be full of garbled characters, as shown below:

deserialization

Serialized files are garbled when opened locally, so deserialization should be used to parse the files into objects.

    public static void main(String[] args) throws Exception{
        List<Person> list = new ArrayList<>();
        FileInputStream fis = new FileInputStream("D:\\person.txt");
        try (ObjectInputStream is = new ObjectInputStream(fis)) {
            list = (List<Person>)is.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        for(Person person : list){ System.out.println(person.toString()); }}Copy the code

Output result:

Person{name=' colt ', age=18, hobby=' colt '}Copy the code

Pay attention to the point

  1. Static and transient variables cannot be serialized
  2. When deserializing, inconsistency between serialVersionUID in the byte stream and serialVersionUID in the entity class throws an exception. SerialVersionUID is default if it is not written.
  3. Serialization implements deep cloning, and every object data referenced by an object is also serialized.

conclusion

  1. Serialization must implement Serializable.
  2. SerialVersionUID is not required.