angelo57 / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

final transient list initializers aren't executed #364

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1.Create a class without a no-arg constructor
2.Give the class a final transient List<String> initialized at declaration
3.Convert to json, and back.

What is the expected output? What do you see instead?
The transient list should have an empty length array.

What version of the product are you using? On what operating system?
GSON 1.7.1, Windows XP, Java 1.7.

Please provide any additional information below.
If there's a no-arg constructor, it's fine. But without one, the transient 
field isn't initialized. Here's an example that shows the problem:

public class NullTransient
{
    public static final Gson GSON;
    static {
        GsonBuilder builder = new GsonBuilder();
        builder.setPrettyPrinting();
        GSON = builder.create();
    }

    final int x;
    final transient List<String> aList = new ArrayList<>();
    NullTransient( int y )
    {
        x = y;
    }

    public static void main( String[] args )
    {
        NullTransient b = new NullTransient( 1 );
        String asJson = GSON.toJson( b );
        NullTransient c = GSON.fromJson( asJson, NullTransient.class );
        System.out.println( b.aList );
        System.out.println( c.aList );
    }
}

Output:
[]
null  <-- this is wrong, it should be an empty list.

You end up in an odd spot where you have a final field that wasn't initialized 
and you can't initialize it later because it's final.

Original issue reported on code.google.com by crkes...@gmail.com on 6 Sep 2011 at 3:08

GoogleCodeExporter commented 9 years ago
I faced the same problem, issue #366

Original comment by hussain.mutawa on 24 Sep 2011 at 3:59

GoogleCodeExporter commented 9 years ago
The core problem is that GSON is constructing your object without executing any 
code, so everything defaults to null. To work around you'll need to add a 
no-args constructor.

Original comment by limpbizkit on 1 Oct 2011 at 5:12