56

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?

python dude
  • 7,980
  • 11
  • 40
  • 53
  • 40
    static transient fields can be detected via reflection. You can write your own serializer to do XML, JSon, etc and you can give this a special meaning if you intend to save static variables as well. – Peter Lawrey Dec 30 '10 at 19:38
  • +1 for getting a use case. My understanding was it's redundant. – Nishant Dec 30 '10 at 19:47
  • 3
    BTW: You can have other modifier combinations which don't make as much sense like public constructor on an abstract class or a protected constructor/method of a final class. – Peter Lawrey Dec 30 '10 at 20:02
  • 1
    With reflection any modifier combination can make sense (more or less) ;-) – python dude Dec 30 '10 at 20:10
  • 1
    @ Peter Lawrey: I suggest you repost your above response as a separate answer so I can mark it as accepted. – python dude Dec 30 '10 at 20:16
  • Thing is: it is probably safe to say that it's one point where the Java specs could have been clearer. They could have prevented *"static transient"* and hence made the point of custom serializers moot. – SyntaxT3rr0r Dec 30 '10 at 20:36

2 Answers2

19

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

Kinda weird that the compiler lets you do that though.

Peter C
  • 6,219
  • 1
  • 25
  • 37
17

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.

Community
  • 1
  • 1
MC Emperor
  • 22,334
  • 15
  • 80
  • 130