GSON Interface InstanceCreator<T>

来源:互联网 发布:elmo控制器 编程 编辑:程序博客网 时间:2024/06/05 13:21

Interface InstanceCreator<T>

Type Parameters:
T - the type of object that willbe created by this implementation.

public interface InstanceCreator<T>

Thisinterface is implemented to create instances of a class that doesnot define a no-args constructor. If you can modify the class, youshould instead add a private, or public no-args constructor.However, that is not possible for library classes, such as JDKclasses, or a third-party library that you do not have source-codeof. In such cases, you should define an instance creator for theclass. Implementations of this interface should be registeredwith GsonBuilder.registerTypeAdapter(Type,Object) method before Gson will be ableto use them.

Letus look at an example where defining an InstanceCreator might beuseful. The Id classdefined 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;   } } 

IfGson encounters an object oftype Id duringdeserialization, it will throw an exception. The easiest way tosolve this problem will be to add a (public or private) no-argsconstructor as follows:

 private Id() {   this(Object.class, 0L); } 

However, let us assume that the developer does not have access tothe source-code ofthe Id class, ordoes not want to define a no-args constructor for it. The developercan solve this problem by definingan InstanceCreator for Id:

 class IdInstanceCreator implements InstanceCreator<Id> {   public Id createInstance(Type type) {     return new Id(Object.class, 0L);   } } 

Notethat it does not matter what the fields of the created instancecontain since Gson will overwrite them with the deserialized valuesspecified in Json. You should also ensure thata new object is returned,not a common object since its fields will be overwritten. Thedeveloper will need toregister IdInstanceCreator withGson as follows:

 Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdInstanceCreator()).create();
0 0