Is it possible to have final transient
fields that are set to any non-default value after serialization in Java? My usecase is a cache variable — that\'s why i
Yes, this is easily possible by implementing the (apparently little known!) readResolve()
method. It lets you replace the object after it is deserialized. You can use that to invoke a constructor that will initialize a replacement object however you want. An example:
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) throws Exception {
X x = new X();
x.name = "This data will be serialized";
x.cache.put("This data", "is transient");
System.out.println("Before: " + x + " '" + x.name + "' " + x.cache);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
new ObjectOutputStream(buffer).writeObject(x);
x = (X)new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())).readObject();
System.out.println("After: " + x + " '" + x.name + "' " + x.cache);
}
public static class X implements Serializable {
public final transient Map
Output -- the string is preserved but the transient map is reset to an empty (but non-null!) map:
Before: test$X@172e0cc 'This data will be serialized' {This data=is transient}
After: test$X@490662 'This data will be serialized' {}