If a class implements Externalizable
, the readExternal()
and writeExternal()
methods must be provided. Unfortunately, these methods are public
and, consequently, can be called by hostile code which can potentially overwrite capable of overwriting the internal state of the object at any point during program execution.
Noncompliant Code Example
This noncompliant code example allows anyone to reset the value of the object due to because of the public
access modifier of the readExternal()
method.
Code Block | ||
---|---|---|
| ||
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // read instance fields this.name = (String)in.readObject(); this.UID = in.readInt(); //... } |
Compliant Solution
This compliant solution is thread-safe solution and allows the first caller to check the initialized
flag after which the instance fields are populated. Finally, the flag is set to true
so that the fields cannot be overwritten.
...