Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Static transient fields

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?

like image 867
python dude Avatar asked Dec 30 '10 19:12

python dude


People also ask

Can transient variables be static?

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.

Can we use transient with static variable in Java?

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.

What are transient fields in Java?

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.

What are transient fields?

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.


2 Answers

Nope - you said it yourself, static fields aren't serialized.

Kinda weird that the compiler lets you do that though.

like image 181
Peter C Avatar answered Oct 11 '22 17:10

Peter C


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.

like image 43
MC Emperor Avatar answered Oct 11 '22 19:10

MC Emperor