欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

对象的序列化与反序列化

程序员文章站 2024-02-26 21:18:34
...

概念
把对象转换成字节序列的为对象的序列化
把字节序列回恢复成对象为反序列化

serialVersionUID序列化版本标识
用于在反序列化时版本的判断。如果没有该属性,在类序列化后如果对该类做了修改,它默认的serialVersionUID就会发生变化,在反序列化时会对比硬盘与Class中的serialVersionUID,如果不相等处于安全考虑会禁止序列化并抛出错误:
1 Exception in thread “main” java.io.InvalidClassException: Customer;
2 local class incompatible:
3 stream classdesc serialVersionUID = -88175599799432325,
4 local class serialVersionUID = -5182532647273106745

序列化相关对象
ObjectOutputStream 序列化输出流
在输出序列化字节数据时不用创建指定的文件名
ObjectInputStream 序列化输入流


    /**
     * 序列化对象
     */
    @Test
    public void objectOutStream() throws IOException {

        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("D:\\aa.txt")));
        objectOutputStream.writeObject(new Person("张三", "重庆",13));
        objectOutputStream.close();


    }

    /**
     * 通过类文件进行反序列化
     */
    @Test
    public void objectInputStream() throws IOException, ClassNotFoundException {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("D:\\aa.txt")));
        Person person = (Person) objectInputStream.readObject();
        System.out.println(person);
        objectInputStream.close();
    }


}


class Person implements Serializable {

    private static final long serialVersionUID = 8289429897296233280L;

    private String name;
    private String home;
    private Integer age;

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

    public String getHome() {
        return home;
    }

    public void setHome(String home) {
        this.home = home;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", home='" + home + '\'' +
                ", age=" + age +
                '}';
    }

Intellij IDEA 自动生成 serialVersionUID
Setting->Inspections->Serialization issues->Serializable class without ’serialVersionUID’
选上以后,在你的class中:Alt+Enter就会提示自动创建serialVersionUID了。
对象的序列化与反序列化
对象的序列化与反序列化

相关标签: java