mercredi 27 septembre 2017

How is GSON creating an instance of a no-zero-arg constructor class? [duplicate]

This question already has an answer here:

In the following example, GSON appears to be able to create an instance of Program (p in the program below) without the use of the declared constructor while also no other zero-arg constructor is present. How is this accomplished by the library?

import com.google.gson.*;
import java.lang.reflect.*;

public class Program
{
    private final String _id;

    private Program(String id)
    {
        System.out.println("Constructor called.");
        _id = id;
    }

    public static void main(String[] args)
    {
        Gson gson = new Gson();

        String json = "{\"_id\":\"id1\"}";
        Program p = gson.fromJson(json, Program.class);

        System.out.println(p._id);

        boolean noArgConstructorAvailable;
        try
        {
            Object ctor = Program.class.getConstructor();
            noArgConstructorAvailable = ctor != null;
        }
        catch(NoSuchMethodException e)
        {
            noArgConstructorAvailable = false;
        }

        System.out.println(noArgConstructorAvailable);
    }
}

Output:

id1
false





Aucun commentaire:

Enregistrer un commentaire