Transient Variable in Java
1. Transient is a keyword
1. Transient is a keyword
2. User very less
3. Transient is used in serialization
4. Variable declared as transient can be avoided from being serialized
5. If we would like to exclude any property of an object from being serialized we mark it transient and then JVM doesn't serialize it.
5. If we would like to exclude any property of an object from being serialized we mark it transient and then JVM doesn't serialize it.
Why do we need transient variable?
6. It provides some control over which variables you want to be serialized and which you want to exclude
7. It gives you flexibility to exclude some of object properties from serialization process
Which variable you should mark transient?
Since we know the purpose of transient keyword or having transient variable its make sense to think about which variable should be marked as transient, any variable whose value can be calculated from other variables doesn't require to be saved.
For example if you have a field called "interest" whose value can be derived from other fields e.g. principle, rate, time etc then there is no need to serialize it.
Example
public class Stock {
private transient Logger logger = Logger.getLogger(Stock.class); //will not serialized
private String symbol; //will be serialized
private BigInteger price; //serialized
private long quantity; //serialized
}
Note:
1) Transient keyword can only be applied to fields or member variable. Applying it to method or local variable is compilation error.
2) Another important point is that you can declare an variable static and transient at same time and java compiler doesn't complain but doing that doesn't make any sense because transient is to
instruct "do not save this field" and static variables are not saved anyway during serialization.
instruct "do not save this field" and static variables are not saved anyway during serialization.
3) In similar way you can apply transient and final keyword together to a variable compiler will not complain but you will face another problem of re-initializing a final variable during de-serialization
.
.
4) Transient variable in java is not persisted or saved when an object gets serialized.
No comments:
Post a Comment