Last active
November 4, 2015 15:23
-
-
Save ixtli/dca738261b0f23cdf059 to your computer and use it in GitHub Desktop.
Why? (Google's GSON library, version 2.4.x, Java8)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.Gson; | |
public class Example | |
{ | |
private class FooExample | |
{ | |
public final String exampleString = "foo"; | |
} | |
private class MooExample | |
{ | |
public final String exampleString; | |
public MooExample() | |
{ | |
exampleString = "moo"; | |
} | |
} | |
public static void main(String [] args) | |
{ | |
final String raw = "{\"exampleString\":\"MODIFIED\"}"; | |
Gson gson = new Gson(); | |
FooExample foo = gson.fromJson(raw, FooExample.class); | |
MooExample moo = gson.fromJson(raw, MooExample.class); | |
System.out.println("Foo:" + foo.exampleString); | |
System.out.println("Moo:" + moo.exampleString); | |
} | |
} |
Gson best practice is to initialize in constructor. I'm pretty sure all the times that this works in our code now where we inline initialize is a coincidence.
So my conclusion, after reading the language specification, is that final
variables are created as so called blank final
s. They can be assigned to once, and only once. What appears to be occurring is that Gson is doing some metaobject manipulation to create heap space for the instance, followed by its own manipulations. Only after that does it call the constructor which would fail to assign because the write-once fields had already been written to.
I wouldn't expect you to be able to assign data to a final variable twice? Otherwise it would be "kinda sorta final-ish"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My output is: