在 Java 中,实现对象序列化可以通过实现 Serializable 接口来完成。下面是一个简单的示例:

import java.io.*;

class Person implements Serializable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class SerializationExample {
    public static void main(String[] args) {
        Person person = new Person('John', 25);

        // 序列化对象
        try {
            FileOutputStream fileOut = new FileOutputStream('person.ser');
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(person);
            out.close();
            fileOut.close();
            System.out.println('对象已序列化');
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化对象
        try {
            FileInputStream fileIn = new FileInputStream('person.ser');
            ObjectInputStream in = new ObjectInputStream(fileIn);
            Person deserializedPerson = (Person) in.readObject();
            in.close();
            fileIn.close();
            System.out.println('对象已反序列化');
            System.out.println('姓名: ' + deserializedPerson.getName());
            System.out.println('年龄: ' + deserializedPerson.getAge());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

在上述示例中,Person 类实现了 Serializable 接口。然后,我们创建了一个 Person 对象并将其序列化到文件 person.ser 中。使用 ObjectOutputStream 类将对象写入文件。

接下来,我们通过使用 ObjectInputStream 类从文件中读取对象,并将其转换为 Person 类型。最后,我们可以访问反序列化后的对象的属性。

请注意,当对象被序列化时,它的所有非静态和非瞬态字段都将被保存。静态字段和瞬态字段不会被序列化。

Java 对象序列化教程:实现和示例

原文地址: https://www.cveoy.top/t/topic/qgWk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录