Let us look at an example where defining an InstanceCreator might be useful. The {@code Id} class defined below does not have a default no-args constructor.
public class Id<T> { private final Class<T> clazz; private final long value; public Id(Class<T> clazz, long value) { this.clazz = clazz; this.value = value; } }
If Gson encounters an object of type {@code Id} during deserialization, it will throw anexception. The easiest way to solve this problem will be to add a (public or private) no-args constructor as follows:
private Id() { this(Object.class, 0L); }
However, let us assume that the developer does not have access to the source-code of the {@code Id} class, or does not want to define a no-args constructor for it. The developercan solve this problem by defining an {@code InstanceCreator} for {@code Id}:
class IdInstanceCreator implements InstanceCreator<Id> { public Id createInstance(Type type) { return new Id(Object.class, 0L); } }
Note that it does not matter what the fields of the created instance contain since Gson will overwrite them with the deserialized values specified in Json. You should also ensure that a new object is returned, not a common object since its fields will be overwritten. The developer will need to register {@code IdInstanceCreator} with Gson as follows:
Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdInstanceCreator()).create();@param < T> the type of object that will be created by this implementation. @author Inderjeet Singh @author Joel Leitch
|
|