让我们考虑以下代码:
public class MyPanel extends JPanel {
private long secretInfo = ...
}
JPanel
是Serializable
。但是,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 = ...
}