Reputation: 59576
Let's consider the following code:
public class MyPanel extends JPanel {
private long secretInfo = ...
}
JPanel
is Serializable
. However, MyPanel
should not be Serializable
ever, because it contains sensitive information.
How to cleanly cancel/prevent the inherited Serializable
aspect from JPanel
?
Upvotes: 1
Views: 1181
Reputation: 128819
Don't extend 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. Composition is often a more powerful relationship.
Upvotes: 2
Reputation: 13779
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 = ...
}
Upvotes: 2
Reputation: 56467
You mark the fields you don't want to serialize as transient
:
private transient long secretInfo = ...
You can still serialize MyPanel
, but its sensitive information won't be serialized.
Also, you could consider an alternative design where the sensitive information is stored in a separate non-serializable class.
Upvotes: 4