TIL-21: What is “transient” in Java?
“Today I learned that the transient keyword is used to mark a variable so that it is not serialized during serialization of the object.”
By definition, transient means lasting only for a short time; impermanent. In Java, it is used in a way to indicate that a variable should not be considered as a part of the object’s permanent state. To be exact, in the Java Language Specification,
Variables may be marked
transient
to indicate that they are not part of the persistent state of an object.
class Person implements Serializable { private int age;
private transient boolean eligibleForDrivingLicense; private void checkEligiblity() {
eligibleForDrivingLicense = age >= 18;
}}
In the above example, we check the driving license status of a person via a method and set it as the field of that object to be used later on. In our case, we do not want to record that status in a file (we do not want eligibleForDrivingLicense field to be serialized) so we mark it with the “transient” keyword. We mark fields whose values can be derived from another fıelds with “transient” to prevent unnecessary serialization of fields.
Apart from our case, it is a good practice to mark fields we consider to be confidential with the transient keyword so that they won’t be serialized and they won’t cause any security problem.
Another case to use the transient keyword on a field — and this is the one I encountered today — is when we have an object that implements serializable but one or more of the fields does not implement serializable thus throwing “java.io.NotSerializableException” when tried to serialize. Imagine the above class with a Map<String, Object> itemsInBag field, Object class in Java, does not implement Serializable interface and cannot be serialized if we try to serialize a Person instance. Marking itemsInBag as “transient” would solve the problem.
Practically we serialized only those fields which represent a state of the instance, after all, serialization is all about to save the state of an object to a file.
References
Cheers!