Note that there are some explanatory texts on larger screens.

plurals
  1. POfinal transient fields and serialization
    text
    copied!<p>Is it possible to have <code>final transient</code> fields that are set to any non-default value after serialization in Java? My usecase is a cache variable — that's why it is <code>transient</code>. I also have a habit of making <code>Map</code> fields that won't be changed (i.e. contents of the map is changed, but object itself remains the same) <code>final</code>. However, these attributes seem to be contradictory — while compiler allows such a combination, I cannot have the field set to anything but <code>null</code> after unserialization.</p> <p>I tried the following, without success:</p> <ul> <li>simple field initialization (shown in the example): this is what I normally do, but the initialization doesn't seem to happen after unserialization;</li> <li>initialization in constructor (I believe this is semantically the same as above though);</li> <li>assigning the field in <code>readObject()</code> — cannot be done since the field is <code>final</code>.</li> </ul> <p>In the example <code>cache</code> is <code>public</code> only for testing.</p> <pre><code>import java.io.*; import java.util.*; public class test { public static void main (String[] args) throws Exception { X x = new X (); System.out.println (x + " " + x.cache); ByteArrayOutputStream buffer = new ByteArrayOutputStream (); new ObjectOutputStream (buffer).writeObject (x); x = (X) new ObjectInputStream (new ByteArrayInputStream (buffer.toByteArray ())).readObject (); System.out.println (x + " " + x.cache); } public static class X implements Serializable { public final transient Map &lt;Object, Object&gt; cache = new HashMap &lt;Object, Object&gt; (); } } </code></pre> <p>Output:</p> <pre><code>test$X@1a46e30 {} test$X@190d11 null </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload