瞬态字段的Java序列化

StK*_*ler 0 java reflection serialization

我正在阅读Thinking in Java 4th Edition.描述了transient字段序列化的奇怪解决方法:

import java.io.*;

public class SerializationTest implements Serializable {
    private String firstData;
    //transient field, shouldn't be serialized.
    transient private String secondData;

    public SerializationTest(String firstData, String test2) {
        this.firstData = firstData;
        this.secondData = test2;
    }

    /**
     * Private method, same signature as in Serializable interface
     *
     * @param stream
     * @throws IOException
     */
    private void writeObject(ObjectOutputStream stream) throws IOException {
        stream.defaultWriteObject();
        stream.writeObject(secondData);
    }

    /**
     * Private method, same signature as in Serializable interface
     *
     * @param stream
     * @throws IOException
     */
    private void readObject(ObjectInputStream stream)
            throws IOException, ClassNotFoundException {
        stream.defaultReadObject();
        secondData = (String) stream.readObject();

    }

    @Override
    public String toString() {
        return "SerializationTest{" +
                "firstData='" + firstData + '\'' +
                ", secondData='" + secondData + '\'' +
                '}';
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream("object.out");
            oos = new ObjectOutputStream(fos);
            SerializationTest sTest = new SerializationTest("First Data", "Second data");
            oos.writeObject(sTest);
        } finally {
            oos.close();
            fos.close();
        }
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream("object.out");
            ois = new ObjectInputStream(fis);
            SerializationTest sTest = (SerializationTest) ois.readObject();
            System.out.println(sTest);
        } finally {
            ois.close();
            fis.close();
        }
        //Output:
        //SerializationTest{firstData='First Data', secondData='Second data'}
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,实现了私有方法writeObjectreadObject.

问题是:

对于ObjectOutputStream和ObjectInputStream使用Reflection访问私有方法的内容?

这样有多少个后门包含在Java中?

Edw*_*uck 6

后门?它一直都在规范中.这是实现对象的非默认序列化的唯一方法.

非默认序列化使您进入序列化驱动程序的位置.您可以向输出流写入任何内容,只要您可以将其读回并在流的另一端构建对象,您就可以了.

这个人决定序列化瞬态字段的事实不是问题,重点是如果你实现自己的序列化方案,你可以做任何你想做的事情.