Java: Static transient fields

JavaSerializationStaticFieldTransient

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Kinda weird that the compiler lets you do that though.

Solution 2 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpython dudeView Question on Stackoverflow
Solution 1 - JavaPeter CView Answer on Stackoverflow
Solution 2 - JavaMC EmperorView Answer on Stackoverflow