Class GenericAdapter<G>

java.lang.Object
edu.uky.cs.nil.tt.io.GenericAdapter<G>
Type Parameters:
G - the class of object whose subclasses will always be written as if they were that class
All Implemented Interfaces:
com.google.gson.TypeAdapterFactory

public class GenericAdapter<G> extends Object implements com.google.gson.TypeAdapterFactory
A generic adapter is used to configure a GsonBuilder to write all subclasses of a given superclass as that superclass.

For example, World is a class that may have many subclasses, but when a world is sent to the server's users, it should be sent as a World object, omitting all the details of its specific runtime type. This code configures a GsonBuilder to do so:


GsonBuilder builder = new GsonBuilder();
GenericAdapter<World> adapter = new GenericAdapter<>(World.class);
builder.registerTypeAdapterFactory(adapter);
Author:
Stephen G. Ware
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    final Class<G>
    The class of object whose subclasses will always be written as if they were this class
  • Constructor Summary

    Constructors
    Constructor
    Description
    Constructs a new generic adapter which will write all subclasses of the given class as that class.
  • Method Summary

    Modifier and Type
    Method
    Description
    <T> com.google.gson.TypeAdapter<T>
    create(com.google.gson.Gson gson, com.google.gson.reflect.TypeToken<T> type)
     

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • type

      public final Class<G> type
      The class of object whose subclasses will always be written as if they were this class
  • Constructor Details

    • GenericAdapter

      public GenericAdapter(Class<G> type)
      Constructs a new generic adapter which will write all subclasses of the given class as that class.
      Parameters:
      type - the superclass whose subclasses will all be written as this class
  • Method Details

    • create

      public <T> com.google.gson.TypeAdapter<T> create(com.google.gson.Gson gson, com.google.gson.reflect.TypeToken<T> type)
      Specified by:
      create in interface com.google.gson.TypeAdapterFactory