可序列化是什么意思?

2022-08-31 07:21:27

一个类在Java中到底意味着什么?或者一般来说,就此而言...Serializable


答案 1

序列化是将对象从内存持久保存到一系列位,例如,用于保存到磁盘上。反序列化则相反 - 从磁盘读取数据以冻结/创建对象。

在您的问题的上下文中,它是一个接口,如果在类中实现,则此类可以由不同的序列化程序自动序列化和反序列化。


答案 2

虽然大多数用户已经给出了答案,但我想为那些需要它的人添加一个例子来解释这个想法:

假设您有一个像下面这样的班级人员:

public class Person implements java.io.Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public String firstName;
    public String lastName;
    public int age;
    public String address;

    public void play() {
        System.out.println(String.format(
                "If I win, send me the trophy to this address: %s", address));
    }
    @Override
    public String toString() {
        return String.format(".....Person......\nFirst Name = %s\nLast Name = %s", firstName, lastName);
    }
}

然后创建一个对象,如下所示:

Person william = new Person();
        william.firstName = "William";
        william.lastName = "Kinaan";
        william.age = 26;
        william.address = "Lisbon, Portugal";

您可以将该对象序列化为多个流。我将对两个流执行此操作:

序列化为标准输出:

public static void serializeToStandardOutput(Person person)
            throws IOException {
        OutputStream outStream = System.out;
        ObjectOutputStream stdObjectOut = new ObjectOutputStream(outStream);
        stdObjectOut.writeObject(person);
        stdObjectOut.close();
        outStream.close();
    }

序列化为文件:

public static void serializeToFile(Person person) throws IOException {
        OutputStream outStream = new FileOutputStream("person.ser");
        ObjectOutputStream fileObjectOut = new ObjectOutputStream(outStream);
        fileObjectOut.writeObject(person);
        fileObjectOut.close();
        outStream.close();
    }

然后:

从文件反序列化:

public static void deserializeFromFile() throws IOException,
            ClassNotFoundException {
        InputStream inStream = new FileInputStream("person.ser");
        ObjectInputStream fileObjectIn = new ObjectInputStream(inStream);
        Person person = (Person) fileObjectIn.readObject();
        System.out.println(person);
        fileObjectIn.close();
        inStream.close();
    }

推荐