Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Externalizable/Serializable and final fields

807580May 5 2009 — edited Nov 4 2009
I've done a bit of searching, both on this forum and the web in general, about how to deal with final fields during de-serialization.

Example Class:
class Example implements Externlizable
{
private final int value;

public Example(int value)
{
this.value=value;
}

public void readExternal(ObjectInput arg0) throws IOException, ClassNotFoundException
{
value=arg0.readInt();
}

public void writeExternal(ObjectOutput arg0) throws IOException
{
arg0.writeInt(value);
}
}
I want the field "value" to be final for a few reasons. Primarily, I want to guarantee the class is immutable once instantiated. Also, final fields can lead to performance gain when those fields are accessed repeatedly. The code example above will not work. The compiler will report and error on the "value=..." line in readExternal. Externalization would work if the readExternal method is modified.

So... How do I work around this? Do I ignore the performance gains and forced immutability of the class? Do I assume that accessing non-final fields is optimized automatically whenever those fields are found to be "immutable" (but then what about changing the value via reflection??)?

On an aside, I'm confused as to why readExternal and writeExternal are member methods instead of static. For instance:
class Example implements Externalizable2
{
private final int value;

public Example(int value)
{
this.value=value;
}

public static Example readExternal(ObjectInput in)
{
return new Example(in.readInt());
}

public static void writeExternal(ObjectOutput out,Example object)
{
out.writeInt(object.value);
}

}
This code, assuming the JVM knew to call the static methods instead of the member methods, would do exactly what I want. Anyone have thoughts on this?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 2 2009
Added on May 5 2009
10 comments
1,560 views