What is the effect of static final transient in Java?
Asked Answered
H

3

9

In the code base I am working on, nearly all variables that are declared static final String are also declared transient.

So I have fields like:

public static final transient String VERSION = "1.0";

I am tempted to remove these transient keywords whenever I spot them, because I think it doesn't serve any purpose.

Is there any difference in behaviour between using transient or not in this case?

Hofuf answered 29/1, 2016 at 11:55 Comment(5)
I assume that you are especially referring to the combination with final, so that #4566153 would not be a reasonable duplicate, right?Slavey
please have a look here :) transient variables – Ruthi RuthBridgehead
Who uses serialization anyway? Remove all transients ! :)Jointer
My question is why you have these VERSION-variables. My guess is that they were hardcoded to "1.0" when the class was created, and then remained unchanged for the years after this. Remove the whole thing if you ask me.Orizaba
@Tobb: VERSION was just an example. It's basically used for all String constantsHofuf
D
12

A static field is implicitly transient (when serializing a static field, its value will be lost anyway). So indeed, no need to declare both.

Disbar answered 29/1, 2016 at 12:3 Comment(2)
Would be great if you could add a source, but it looks like it's the correct answer anyway.Hofuf
When you say the value is lost, does the field be part of the serialization without a value(say null) or does the field never feature as a property ?Polity
O
2

The transient keyword on a variable will ensure that the variable is not part of the serialized object when serializing. If your class is not serializable, nor a JPA entity (which uses the transient keyword to avoid storing variables in the database), removing it should be fine.

Orizaba answered 29/1, 2016 at 12:0 Comment(2)
Most of these classes do implement SerializableHofuf
Ok, as the other answer states, static members aren't serialized anyways. #11001475Orizaba
J
1

static members are associated with a class not with the object, hence on deserialization you will see the value you passed on, as opposed to the default values shown while using transient. To have a better understanding try to change the value of the variables after serialization and then on deserialization you will see that the values of serialized members are same but static one has changed. As per the transient final ,final variables do participate in serialization directly by thier values,hence no use of declaring a final variable as transient.

Jessiejessika answered 24/9, 2019 at 3:6 Comment(1)
I may be missing something, but I don't see what this adds to the accepted answer.Hofuf

© 2022 - 2024 — McMap. All rights reserved.