Monday, June 11, 2012

Transient variable can't be final or static?

The modifier transient can be applied to field members of a class to turn off serializationon these field members. Every field marked as transient will not be serialized. You usethe transient keyword to indicate to the Java virtual machine that the transient variable isnot part of the persistent state of an object.Java classes often hold some globally relevant value in a static class variable. The static

member fields belong to class and not to an individual instance. The concept of serialization is concerned with the object's current state. Only data associated with aspecific instance of a class is serialized, therefore static member fields are ignored duringserialization (they are not serialized automatically), because they do not belong to theserialized instance, but to the class. To serialize data stored in a static variable one must provide class-specific serialization.Surprisingly, the java compiler does not complaint if you declare a static member field astransient. However, there is no point in declaring a static member field as transient, sincetransient means: "do not serialize” and static fields would not be serialized anyway.On the other hand, an instance member field declared as final could also be transient, butif so, you would face a problem a little bit difficult to solve: As the field is transient, itsstate would not be serialized, it implies that, when you deserialize the object you wouldhave to initialize the field manually, however, as it is declared final, the compiler wouldcomplaint about it.For instance, maybe you do not want to serialize your class' logger, then you declared itthis way: private transient final Log log = LogFactory.getLog(EJBRefFactory.class); Now, when you deserialize the class your logger will be a null object, since it wastransient. Then you should initialize the logger manually after serialization or during theserialization process. But you can't, because logger is a final member as well.

No comments:

Post a Comment