Java: Static transient fields
Asked Answered
T

2

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?

Transcription answered 30/12, 2010 at 19:35 Comment(6)
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.Segno
+1 for getting a use case. My understanding was it's redundant.Versify
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.Segno
With reflection any modifier combination can make sense (more or less) ;-)Transcription
@ Peter Lawrey: I suggest you repost your above response as a separate answer so I can mark it as accepted.Transcription
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.Belgium
T
18

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

Kinda weird that the compiler lets you do that though.

Teodorateodorico answered 30/12, 2010 at 19:37 Comment(5)
They are not serialized by the built in Java serializer. However other serializers can behave differently.Segno
And even with another serializer, the point of saving static fields is...?Teodorateodorico
@Peter, By the way serialVersionUID would be an exception.Patrizio
@UstamanSangat Or one can just drop "non-ObjectO" paradigms and be happy with standard serialization behaviors ..Voorhees
Nothing 'weird' about it. It's legal syntax, with a plausible implementation. No reason why the compiler should get involved in the Java Object Serialization Specification.Trumpery
G
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.

Giuliana answered 15/9, 2015 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.