Java(1.8)原生反序列化方式创建对象不会执行构造方法

证明如下:

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        class X implements Serializable {
            public X(){
                System.out.println(this);
            }
        }

        X x = new X();
        ByteOutputStream out = new ByteOutputStream();

        try(ObjectOutputStream oos = new ObjectOutputStream(out)) {
            oos.writeObject(x);
            oos.flush();
        }
        byte[] bytes = out.getBytes();
        try(ObjectInputStream ois = new ObjectInputStream(new ByteInputStream(bytes, bytes.length))) {
            Object o = ois.readObject();
            System.out.println(o==x);
        }
    }

执行结果如下:

com.learn.spring.test.A$1X@78308db1
false

posted @ 2019-08-03 21:02  安大地  阅读(247)  评论(0)    收藏  举报