Summarize two methods of serializing Java objects

  • 2021-10-15 10:26:41
  • OfStack

Why Java objects need to be serialized

Serialization can convert objects into binary streams, so that objects can be conveniently transmitted and saved in the network.

Ways to Implement Serialization

Implement Serializable interface Implement Externalizable interface

** The difference between the two interfaces is that the **Serializable interface automatically marks all properties of an object as serializable. By default, the Externalizable interface does not mark any attributes that can be serialized. If serialization is required, you need to override two methods, writeExternal () and readExternal (), and then mark the object attributes that need to be serialized in these two methods.

The implementation of these two interfaces only means that the object can be serialized, and the real serialization operation requires ObjectOutputStream object operation. Next, serialization is embodied in coding.

First, write a tool class for serialization operation, which is used to realize serialization and deserialization.


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 *  Serialization operation tool class 
 * @author  Yang 33
 * @date 2020/6/21 15:22
 */
public class SerializeUtil {
    /**
     *  Convert an object to a byte array 
     * @param object  Objects to be serialized 
     * @return
     * @throws IOException
     */
    public static byte[] serialize(Object object) throws IOException{
        if(object == null){
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        return byteArrayOutputStream.toByteArray();
    }

    /**
     *  Deserialization 
     * @param bytes  Object byte array 
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object unserialize(byte[] bytes) throws IOException, ClassNotFoundException{
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        return objectInputStream.readObject();
    }
}

First, implement an Serializable interface


/**
 * @author  Yang 33
 * @date 2020/6/21 14:20
 */
public class Owner implements Serializable {
    private String name;

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

Under test:


import java.io.IOException;
/**
 * @author  Yang 33
 * @date 2020/6/21 14:54
 */
public class Demo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Owner owner = new Owner();
        owner.setName(" Li 4");
        // Serialization 
        byte[] serialize = SerializeUtil.serialize(owner);
        System.out.println(" Effect of serialization: " + serialize);
        // Deserialization 
        owner = (Owner)SerializeUtil.unserialize(serialize);
        System.out.println(" Effect of deserialization: " + owner.getName());
    }
}

Console print results:

Effect of serialization: [B @ 58ca40be
Effect of deserialization: Li 4

If this name field does not need to be serialized, it can be decorated with the keyword transient, such as:


private transient String name;

In Test 1, the name field will not be serialized, and the deserialized value will be null.

Effect of serialization: [B @ 4ca49360
Effect of deserialization: null

Implement another Externalizable interface


/**
 * @author  Yang 33
 * @date 2020/6/21 14:20
 */
public class Medium implements Externalizable {
    private String name;
    private String sex;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(name);
        out.writeObject(sex);
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = (String) in.readObject();
        sex = (String) in.readObject();
    }
}

Under test:


import java.io.IOException;
/**
 * @author  Yang 33
 * @date 2020/6/21 14:54
 */
public class Demo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Medium medium = new Medium();
        medium.setName(" Li 4");
        medium.setSex(" Female ");
        // Serialization 
        byte[] serialize = SerializeUtil.serialize(medium);
        System.out.println(" Effect of serialization: " + serialize);
        // Deserialization 
        medium = (Medium)SerializeUtil.unserialize(serialize);
        System.out.println(" Effect of deserialization: " + medium.getName());
        System.out.println(" Effect of deserialization: " + medium.getSex());
    }
}

Console print results:

Effect of serialization: [B @ 71d9a2ab
Effect of deserialization: Li 4
Effect of deserialization: female

If the field sex does not need to be serialized, the code that sets the sex field can be removed from the methods writeExternal () and readExternal (). Finally, the sex field will not be serialized, and the value obtained after deserialization will be null.

Effect of serialization: [B @ 746c2f2
Effect of deserialization: Li 4
Effect of deserialization: null


Related articles: