T
- the type of object that will be created by this implementation.public interface InstanceCreator<T>
GsonBuilder.registerTypeAdapter(Type, Object)
method before Gson will be able to use
them.
Let us look at an example where defining an InstanceCreator might be useful. The
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 Id
during deserialization, it will throw an
exception. 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
Id
class, or does not want to define a no-args constructor for it. The developer
can solve this problem by defining an InstanceCreator
for 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 IdInstanceCreator
with Gson as follows:
Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdInstanceCreator()).create();
Modifier and Type | Method and Description |
---|---|
T |
createInstance(Type type)
Gson invokes this call-back method during deserialization to create an instance of the
specified type.
|
T createInstance(Type type)
new
to create a new instance.type
- the parameterized T represented as a Type
.Copyright © 2008–2015 Google, Inc.. All rights reserved.