java序列号与反序列化

82 阅读1分钟

先举个java序列化的例子,然后再用readObject阻止反序列化。


import java.io.Serializable;

public class MyObject implements Serializable {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializationExample {

    public static void main(String[] args) {
        MyObject obj = new MyObject("John", 30);

        try {
            FileOutputStream fos = new FileOutputStream("/Users/jeff/Documents/http/myobject.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(obj);
            oos.close();
            fos.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializationExample {

    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("/Users/jeff/Documents/http/myobject.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            MyObject obj = (MyObject) ois.readObject();
            ois.close();
            fis.close();
            System.out.println("Name: " + obj.getName());
            System.out.println("Age: " + obj.getAge());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

反序列化的结果为

image.png

在有些场景,比如枚举类,不允许反序列化,如何防止java类被反序列化。

自行编写readObject()函数,用于对象的反序列化构造。

例如实体上加上

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

public class MyObject implements Serializable {
//    private static final String serialVersionUID = "111112222233333";
    private static final long serialVersionUID = -4392658638228508589L;

    private int id;
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    private void readObject(ObjectInputStream objectInputStream ) throws IOException, ClassNotFoundException {
        // 调用默认的反序列化函数
        objectInputStream.defaultReadObject();
        throw new IllegalArgumentException("不能反序列化!");
    }
}

再次反序列化的时候,则报错了。

image.png