How to serialize Java objects? Take a look at these two methods!

Posted by turdferguson on Sun, 30 Jan 2022 00:41:18 +0100

Why do Java objects need to be serialized

  • Serialization can convert objects into binary streams, and objects can be easily transmitted and saved in the network.

How to implement serialization

  • Implement Serializable interface
  • Implement Externalizable interface

**The difference between the two interfaces is: * * the Serializable interface will automatically mark all attributes of the object as Serializable. The Externalizable interface does not mark any attribute for serialization by default. If serialization is required, two methods need to be rewritten, writeExternal() and readExternal(), and then mark the object attribute to be serialized in these two methods.

Implementing these two interfaces only means that the object can be serialized. For real serialization operation, ObjectOutputStream object operation is required. Next, we use encoding to embody serialization.

1. First write a tool class for serialization operation 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 object to byte array
     * @param object Objects that need 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();
    }
}

Let's implement a Serializable interface first

/**
 * @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 Si");
        //serialize
        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 Si

If the name field does not need to be serialized, you can use the keyword transient to modify it, for example:

private transient String name;

At this time, test that the name field will not be serialized, and the value obtained after deserialization will be null.

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

Then implement an 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 Si");
        medium.setSex("female");
        //serialize
        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 Si
 Effect of deserialization: Female

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

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

Now, this knowledge sharing is over. Thank you for your encouragement in my writing. I will continue to work hard.

last

I also prepared a systematic learning package for architects and BAT interview materials for your reference and learning, You can get it here for free

The knowledge system has been sorted out (source code, notes, PPT, learning video) for free.

ttps://docs.qq.com/doc/DSmxTbFJ1cmN1R2dB)**

The knowledge system has been sorted out (source code, notes, PPT, learning video) for free.

[external chain picture transferring... (img-DHT1KTJd-1623617052583)]

[external chain picture transferring... (img-f7huB2Av-1623617052584)]

[external chain picture transferring... (IMG sftgrriz-1623617052585)]

Topics: Java Interview Programmer