Class TypeReference<T>

java.lang.Object
com.alibaba.fastjson2.TypeReference<T>

public abstract class TypeReference<T> extends Object
Represents a generic type T. Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

This syntax cannot be used to create type literals that have wildcard parameters, such as Class<T> or List<? extends CharSequence>.

For example, to create a type literal for List<String>, you can create an empty anonymous inner class:


 TypeReference<List<String>> typeReference = new TypeReference<List<String>>(){};
 
For example, use it quickly
String text = "{\"id\":1,\"name\":\"kraity\"}";
 User user = new TypeReference<User>(){}.parseObject(text);
 
  • Field Details

    • type

      protected final Type type
    • rawType

      protected final Class<? super T> rawType
  • Constructor Details

    • TypeReference

      public TypeReference()
      Constructs a new type literal. Derives represented class from type parameter.

      Clients create an empty anonymous subclass. Doing so embeds the type parameter in the anonymous class's type hierarchy, so we can reconstitute it at runtime despite erasure.

    • TypeReference

      public TypeReference(Type... actualTypeArguments)
      E.g.
      
       Class<T> klass = ...;
       TypeReference<Response<T>> ref = new TypeReference<Response<T>>(new Type[]{klass}){};
       
      Parameters:
      actualTypeArguments - an array of Type objects representing the actual type arguments to this type
      Throws:
      NullPointerException - If the actualTypeArguments is null or empty
      Since:
      2.0.2
  • Method Details