If a class implements Externalizable
, public readExternal
and writeExternal
methods have to be provided. Unfortunately, these methods are public and thus can be called by hostile code which can potentially overwrite the internal state of the object through multiple calls.
Noncompliant Code Example
This noncompliant example allows anyone to reset the value of the object due to the public
access modifier of the readExternal
method.
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // read instance fields this.name = (String)in.readObject(); this.UID = in.readInt(); //... }
Compliant Solution
This thread-safe solution allows the first caller to set an initialized
flag following which, the instance fields are populated.
public synchronized void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { if (!initialized) { // read instance fields this.name = (String)in.readObject(); this.UID = in.readInt(); //... initialized = true; } else { throw new IllegalStateException(); } }