8

我正在阅读有关 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 接口?

4

1 回答 1

-4

是的,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();
        }
    }
}

另请阅读有关序列化的本指南

于 2013-06-14T06:44:41.583 回答