让我们考虑以下代码:

public class MyPanel extends JPanel {

    private long secretInfo = ...

}


JPanelSerializable。但是,MyPanel永远都不应该是Serializable,因为它包含敏感信息。

如何彻底取消/防止从Serializable继承的JPanel方面?

最佳答案

您可以使用以下方法之一:

public class MyPanel extends JPanel {
    private long secretInfo = ...

    // refuse to be serialized!
    private void writeObject(ObjectOutputStream out) throws IOException {
        throw new IllegalStateException("MyPanel cannot be serialized");
    }
}


要么

public class MyPanel extends JPanel {
    // flag the serialization mechanism to ignore
    // sensitive information
    private transient long secretInfo = ...
}

10-07 23:24