简体   繁体   English

如何使继承可序列化 class 的 class 不能序列化?

[英]How to make a class inheriting of serializable class not serializable ever?

Let's consider the following code:让我们考虑以下代码:

public class MyPanel extends JPanel {

    private long secretInfo = ...

}

JPanel is Serializable . JPanel是可Serializable的。 However, MyPanel should not be Serializable ever, because it contains sensitive information.但是, MyPanel永远不应该是Serializable ,因为它包含敏感信息。

How to cleanly cancel/prevent the inherited Serializable aspect from JPanel ?如何彻底取消/防止从JPanel继承的Serializable方面?

You mark the fields you don't want to serialize as transient :您将不想序列化的字段标记为transient

private transient long secretInfo = ...  

You can still serialize MyPanel , but its sensitive information won't be serialized.您仍然可以序列化MyPanel ,但它的敏感信息不会被序列化。

Also, you could consider an alternative design where the sensitive information is stored in a separate non-serializable class.此外,您可以考虑另一种设计,其中敏感信息存储在单独的不可序列化 class 中。

You can use one of the following approaches:您可以使用以下方法之一:

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");
    }
}

or或者

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

Don't extend JPanel.不要扩展 JPanel。 Problem solved.问题解决了。 Try something like this instead:尝试这样的事情:

class MyPanel {
    void doSomething();
    String getSomeValue();
    JPanel getDisplayComponent();
}

MyPanel logically represents a panel in your app, but there's no particular requirement for it to extend JPanel. MyPanel 在逻辑上表示您的应用程序中的一个面板,但对于扩展 JPanel 没有特别的要求。 Composition is often a more powerful relationship.组合通常是一种更强大的关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM