将对象进行序列化可以使对象能够持久化到磁盘中或者进行网络传输,从而使对象脱离程序运行而独立存在,这对于分布式应用很有意义。要实现序列化对象需要实现Seriazable接口或者Externalizable接口。通常,对于javaBean类都建议实现Seriazable接口。下面实现了一个简单的对象序列化的demo。

public 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 void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}
    public class WriteObject {
        public static void main(String[] args) {
            try (ObjectOutputStream oos = new ObjectOutputStream(
                    new FileOutputStream("test.txt"));) {
                Person person = new Person("wkx", 3);
                oos.writeObject(person);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }