As mentioned in the article
http://www.xyzws.com/Javafaq/can-transient-variables-be-declared-as-final-or-static/0
creating a field transient will prevent its serialization with one exception:
There is only one exception to this rule, and this is when a member of the final field of the transient is initialized as a constant expression like those defined in JLS 15.28 . Therefore, field members declared in this way retain their expression of constant value even after deserializing the object.
If you visit the mentioned JSL, you will find out that
A constant expression is an expression indicating the value of a primitive type or String
But Integer not a primitive type, and it is not a String, so it is not considered a constant expression candidate, so its value will not remain after serialization.
Demo:
class SomeClass implements Serializable { public transient final int a = 10; public transient final Integer b = 10; public transient final String c = "foo"; public static void main(String[] args) throws Exception { SomeClass sc = new SomeClass(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(sc); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream( bos.toByteArray())); SomeClass sc2 = (SomeClass) ois.readObject(); System.out.println(sc2.a); System.out.println(sc2.b); System.out.println(sc2.c); } }
Output:
10 null foo
source share