java序列化如何在内部工作?

时间:2013-06-14 06:16:22

标签: java serialization

我正在阅读关于Java序列化的内容,并且知道如果实现了Serializable接口,那么类就被序列化了。

但Serializable是一个标记界面。那么JVM如何知道应该采用哪种方法进行序列化或反序列化呢?

根据我的理解,接口中声明的方法是通过多态性调用的。

我会在下面举例说明我的问题。

    public class MySerializable implements Serializable{

    public void serialize(){

      //Some code to serialize to a file output stream.
    }

    public void deSerialize(){

      //Some code to de-serialize to a file input stream.
    }


}

那么现在JVM将如何调用serialize / deSerialize方法?

如果我必须通过代码手动调用它们,为什么编译器应该知道Serializable接口是否已实现?

1 个答案:

答案 0 :(得分:-1)

是的,Serializable接口没有任何实现方法。如果需要序列化对象,则对象必须实现Serializable接口。接下来,您可以使用对象执行序列化/反序列化过程,例如使用ObjectOutputStream和ObjectInputStream对象。

没有什么例子。

类,需要序列化/反序列化:

import java.io.Serializable;

public class ObjectToSerialize implements Serializable {

    private static final long serialVersionUID = 7526472295622776147L;

    private String firstName;
    private String lastName;

    public ObjectToSerialize(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @Override
    public String toString() {
        return getFirstName() + " " + getLastName();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ObjectToSerialize that = (ObjectToSerialize) o;
        return firstName.equals(that.firstName) && lastName.equals(that.lastName);
    }
}

带序列化/反序列化方法的类:

import java.io.*;

public class ObjectSerialization {

    public static void saveObject(Serializable object, String path) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) {
            oos.writeObject(object);
        }
    }

    public static Object loadObject(String path) throws ClassNotFoundException, IOException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))) {
            return ois.readObject();
        }
    }

    public static void main(String[] args) {
        ObjectToSerialize object = new ObjectToSerialize("Eldar", "Agalarov");
        try {
            String path = "C:/object.bin";
            saveObject(object, path);
            System.out.println("Object serialized: " + object);

            ObjectToSerialize deserializedObject = (ObjectToSerialize) loadObject(path);
            System.out.println("Object deserialized: " + deserializedObject);
            System.out.println("They are equals: " + object.equals(deserializedObject));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

另请阅读this guide about serialization