Here's my sample code:
public class ExternalizableClass implements Externalizable
{
final int id;
public ExternalizableClass()
{
id = 0;
}
public ExternalizableClass(int i)
{
id = i;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException
{
out.writeInt(id);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
id = in.readInt();
}
@Override
public String toString()
{
return "id: " + id;
}
}
It fails to compile because id = in.readInt();
gives Error:(36, 5) java: cannot assign a value to final variable id
. However, I can think of real use cases where an immutable field, such as id, needs to be externalized, while we also want to preserve its immutability.
So what's the correct way to resolve this issue?