Skip to content

Instantly share code, notes, and snippets.

@ixtli
Last active November 4, 2015 15:23
Show Gist options
  • Save ixtli/dca738261b0f23cdf059 to your computer and use it in GitHub Desktop.
Save ixtli/dca738261b0f23cdf059 to your computer and use it in GitHub Desktop.
Why? (Google's GSON library, version 2.4.x, Java8)
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);
}
}
@ixtli
Copy link
Author

ixtli commented Nov 4, 2015

My output is:

Foo:foo
Moo:MODIFIED

@supertommy
Copy link

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.

@ixtli
Copy link
Author

ixtli commented Nov 4, 2015

So my conclusion, after reading the language specification, is that final variables are created as so called blank finals. 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.

@drchopchop
Copy link

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