Class TypeReference<T>

  • All Implemented Interfaces:
    Comparable<TypeReference<T>>

    public class TypeReference<T>
    extends Object
    implements Comparable<TypeReference<T>>
    This generic abstract class is used for obtaining full generics type information Class is based on ideas from http://gafter.blogspot.com/2006/12/super-type-tokens.html, Additional idea (from a suggestion made in comments of the article) is to require bogus implementation of Comparable (any such generic interface would do, as long as it forces a method with generic type to be implemented). to ensure that a Type argument is indeed given.

    Usage is by sub-classing: here is one way to instantiate reference to generic type List<Integer>:

      TypeReference ref = new TypeReference<List<Integer>>() { };
      
    • Constructor Detail

      • TypeReference

        protected TypeReference()
        Constructs a new generic type, deriving the generic type and class from type parameter. Note that this constructor is protected, users should create a (usually anonymous) subclass as shown above.
        Throws:
        IllegalArgumentException - in case the generic type parameter value is not provided by any of the subclasses.
      • TypeReference

        public TypeReference​(Type typeReference)
        Constructs a new generic type, supplying the generic type information and deriving the class.
        Parameters:
        typeReference - the generic type.
        Throws:
        IllegalArgumentException - if typeReference is null or not an instance of Class or ParameterizedType whose raw type is an instance of Class.
    • Method Detail

      • getType

        public final Type getType()
        Retrieve the type represented by the generic type instance.
        Returns:
        the actual type represented by this generic type instance.
      • getRawType

        public final Class<?> getRawType()
        Returns the object representing the class or interface that declared the type represented by this generic type instance.
        Returns:
        the class or interface that declared the type represented by this generic type instance.
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class Object
      • compareTo

        public int compareTo​(TypeReference<T> o)
        The only reason we define this method (and require implementation of Comparable) is to prevent constructing a reference without type information.
        Specified by:
        compareTo in interface Comparable<T>