I just found out in Java you can declare a field 'static transient' - the compiler doesn't complain. This doesn't seem to be useful in any way since static fields are not serialized, as we all know.
But I wonder, is there actually a case where 'static transient' fields are useful?
The main difference between the two ( static versus transient ) is that static variables exist only once per transaction, but transient variables can exist many times. In other words, static variables have a global scope, while transient variables have a local scope.
Since the static variable is not a part of the object state because of this declaring the static variable as transient there is not use.
Transient in Java is used to indicate that a field should not be part of the serialization process. The modifier Transient can be applied to member variables of a class to turn off serialization on these member variables. Every field that is marked as transient will not be serialized.
transient Fields: Variables may be marked transient to indicate that they are not part of the persistent state of an object. For example, you may have fields that are derived from other fields, and should only be done so programmatically, rather than having the state be persisted via serialization.
Nope - you said it yourself, static fields aren't serialized.
Kinda weird that the compiler lets you do that though.
In most cases, it is not useful. Static fields are indeed not serialized by the default serializer.
However, static
transient
fields can be detected via reflection. If someone writes its own serializer and he wants to also serialize static fields, then he might take the transient
keyword in consideration and skip the serialization of that particular field.
PS: This answer is posted for the sake of completeness, and is based on Peter Lawrey's comment. Credits to him.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With