final transient fields and serialization

后端 未结 5 1830
无人及你
无人及你 2020-12-13 03:46

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

5条回答
  •  一个人的身影
    2020-12-13 04:06

    You can change the contents of a field using Reflection. Works on Java 1.5+. It will work, because serialization is performed in a single thread. After another thread access the same object, it shouldn't change the final field (because of weirdness in the memory model & reflaction).

    So, in readObject(), you can do something similar to this example:

    import java.lang.reflect.Field;
    
    public class FinalTransient {
    
        private final transient Object a = null;
    
        public static void main(String... args) throws Exception {
            FinalTransient b = new FinalTransient();
    
            System.out.println("First: " + b.a); // e.g. after serialization
    
            Field f = b.getClass().getDeclaredField("a");
            f.setAccessible(true);
            f.set(b, 6); // e.g. putting back your cache
    
            System.out.println("Second: " + b.a); // wow: it has a value!
        }
    
    }
    

    Remember: Final is not final anymore!

提交回复
热议问题