Class Types


  • public final class Types
    extends Object
    Utility class for working with generic types, fields and methods.

    Logic and inspiration were drawn from the following excellent libraries:

    • Google Guava's com.google.common.reflect package.
    • Apache Commons Lang 3's org.apache.commons.lang3.reflect package.
    • GenTyRef (Generic Type Reflector), a library for runtime generic type introspection.
    Author:
    Curtis Rueden, Gabriel Selzer, David Kolb
    • Method Detail

      • name

        public static String name​(Type t)
        Gets a string representation of the given type.
        Parameters:
        t - Type whose name is desired.
        Returns:
        The name of the given type.
      • isInstance

        public static boolean isInstance​(Object obj,
                                         Class<?> dest)
        Checks whether the given object can be cast to the specified type.
        Returns:
        true If the destination class is assignable from the source object's class, or if the source object is null and destination class is non-null.
        See Also:
        cast(Object, Class)
      • cast

        public static <T> T cast​(Object src,
                                 Class<T> dest)
        Casts the given object to the specified type, or null if the types are incompatible.
      • enumValue

        public static <T> T enumValue​(String name,
                                      Class<T> dest)
        Converts the given string value to an enumeration constant of the specified type.
        Parameters:
        name - The value to convert.
        dest - The type of the enumeration constant.
        Returns:
        The converted enumeration constant.
        Throws:
        IllegalArgumentException - if the type is not an enumeration type, or has no such constant.
      • raw

        public static Class<?> raw​(Type type)
        Gets the (first) raw class of the given type.
        • If the type is a Class itself, the type itself is returned.
        • If the type is a ParameterizedType, the raw type of the parameterized type is returned.
        • If the type is a GenericArrayType, the returned type is the corresponding array class. For example: List<Integer>[] => List[].
        • If the type is a type variable or wildcard type, the raw type of the first upper bound is returned. For example: <X extends Foo & Bar> => Foo.

        If you want all raw classes of the given type, use raws(java.lang.reflect.Type).

        Parameters:
        type - The type from which to discern the (first) raw class.
        Returns:
        The type's first raw class.
      • raws

        public static List<Class<?>> raws​(Type type)
        Gets all raw classes corresponding to the given type.

        For example, a type parameter A extends Number & Iterable will return both Number and Iterable as its raw classes.

        Parameters:
        type - The type from which to discern the raw classes.
        Returns:
        List of the type's raw classes.
        See Also:
        raw(java.lang.reflect.Type)
      • typeOf

        public static Type typeOf​(Field field,
                                  Class<?> type)
        Returns the exact generic type of the given field, as viewed from the given type. This may be narrower than what Field.getGenericType() returns, if the field is declared in a superclass, or type has a type parameter that is used in the type of the field.

        For example, suppose we have the following three classes:

         public class Thing<T> {
                 public T thing;
         }
        
         public class NumberThing<N extends Number> extends Thing<N> {}
        
         public class IntegerThing extends NumberThing<Integer> {}
         
        Then this method operates as follows:
         field = Classes.field(Thing.class, "thing");
        
         field.getType(); // Object
         field.getGenericType(); // T
        
         Types.typeOf(field, Thing.class); // T
         Types.typeOf(field, NumberThing.class); // N extends Number
         Types.typeOf(field, IntegerThing.class); // Integer
         
      • paramTypesOf

        public static Type[] paramTypesOf​(Method m,
                                          Type type)
        Returns the exact parameter types of the given method in the given type. This may be different from m.getGenericParameterTypes() when the method was declared in a superclass, or type has a type parameter that is used in one of the parameters, or type is a raw type.
        Parameters:
        m -
        type -
      • returnTypeOf

        public static Type returnTypeOf​(Method m,
                                        Type type)
        Returns the exact return type of the given method in the given type. This may be different from m.getGenericReturnType() when the method was declared in a superclass, or type has a type parameter that is used in the return type, or type is a raw type.
        Parameters:
        m -
        type -
      • isAssignable

        public static boolean isAssignable​(Type source,
                                           Type target)
        Discerns whether it would be legal to assign a reference of type source to a reference of type target.
        Parameters:
        source - The type from which assignment is desired.
        target - The type to which assignment is desired.
        Returns:
        True if the source is assignable to the target.
        Throws:
        NullPointerException - if target is null.
        See Also:
        Class.isAssignableFrom(Class)
      • isAssignable

        public static boolean isAssignable​(Type type,
                                           Type toType,
                                           Map<TypeVariable<?>,​Type> typeVarAssigns)

        Checks if the subject type may be implicitly cast to the target type following the Java generics rules.

        Parameters:
        type - the subject type to be assigned to the target type
        toType - the target type
        typeVarAssigns - optional map of type variable assignments
        Returns:
        true if type is assignable to toType.
      • superTypeOf

        public static Type superTypeOf​(Type type,
                                       Class<?> searchClass)
        Finds the most specific supertype of type whose erasure is searchClass. In other words, returns a type representing the class searchClass plus its exact type parameters in type.
        • Returns an instance of ParameterizedType if searchClass is a real class or interface and type has parameters for it
        • Returns an instance of GenericArrayType if searchClass is an array type, and type has type parameters for it
        • Returns an instance of Class if type is a raw type, or has no type parameters for searchClass
        • Returns null if searchClass is not a superclass of type.

        For example, with class StringList implements List<String>, superTypeOf(StringList.class, Collection.class) returns a ParameterizedType representing Collection<String>.

        Parameters:
        type -
        searchClass -
      • commonSuperTypeOf

        public static Type commonSuperTypeOf​(Type... types)
        Determines the greatest common supertype of all types in the input array.

        When multiple suitable interfaces are found, a wildcard with all such interfaces as upper bounds is returned. If only one suitable interface is found, the return will be the interface itself (i.e. not a wildcard).

        Parameters:
        types - The array of subtypes, for which the supertype is found.
        Returns:
        a Type that is a supertype of all Types in the types array.
      • component

        public static Type component​(Type type)
        Gets the component type of the given array type, or null if not an array.

        If you have a Class, you can call Class.getComponentType() for a narrower return type.

        This is the opposite of array(Type).

      • typeParamsOf

        public static Type[] typeParamsOf​(Type src,
                                          Class<?> superclass)
        Obtains the type parameters of Type src with respect to the Class dest. When src has no type parameters (or is not a subclass of dest), an empty array is returned.
        Parameters:
        src - - the Type whose type parameters will be returned.
        superclass - - the Class against which we want the type parameters of src
        Returns:
        an array of Types denoting the type
      • containsTypeVars

        public static boolean containsTypeVars​(Type type)
        Learn, recursively, whether any of the type parameters associated with type are bound to variables.
        Parameters:
        type - the type to check for type variables
        Returns:
        boolean
      • isRecursive

        public static boolean isRecursive​(Type type)
        Checks if the given Type is recursively typed: that is if it's a ParameterizedType with a self-referential type parameter.
        Parameters:
        type - Type of interest to interrogate
        Returns:
        True if the given type is recursively parameterized, False otherwise
      • isRecursiveBound

        public static boolean isRecursiveBound​(Type refType,
                                               Type typeBound)
        Helper method to detect if a particular bound, typeBound, of a reference type, refType, is a recursive type parameter: that is, if typeBound itself has a type argument equal to refType.
        Parameters:
        refType - Base type to check
        typeBound - A bound of refType
        Returns:
        True if typeBound is parameterized with a type argument that is itself equal to refType
      • varsSatisfied

        public static boolean varsSatisfied​(Map<TypeVariable<?>,​Type> typeVarAssigns)
        Determines whether or not specified types satisfy the bounds of their mapped type variables. When a type parameter extends another (such as <T, S extends T>), uses another as a type parameter (such as <T, S extends Comparable>>), or otherwise depends on another type variable to be specified, the dependencies must be included in typeVarAssigns.
        Parameters:
        typeVarAssigns - specifies the potential types to be assigned to the type variables, not null.
        Returns:
        whether the types can be assigned to their respective type variables.
      • unroll

        public static Type[] unroll​(Type[] typesToMap,
                                    Map<TypeVariable<?>,​Type> typeVarAssigns)
        Map type vars in specified type list to types using the specified map. In doing so, type vars mapping to other type vars will not be followed but just replaced.
        Parameters:
        typesToMap -
        typeVarAssigns -
      • unroll

        public static Type unroll​(Type typeToMap,
                                  Map<TypeVariable<?>,​Type> typeVarAssigns)
        Map type vars in the specified type to a type using the specified map. In doing so, type vars mapping to other type vars will not be followed but just replaced.
        Parameters:
        typeToMap -
        typeVarAssigns -
      • unroll

        public static Type unroll​(Map<TypeVariable<?>,​Type> typeVarAssigns,
                                  Type type,
                                  boolean followTypeVars)
        Get a type representing type with variable assignments "unrolled."
        Parameters:
        typeVarAssigns - a Map of the type assignments for the type variables in each type in the inheritance hierarchy of type.
        type - the type to unroll variable assignments for
        followTypeVars - whether a TypeVariable should be recursively followed if it maps to another TypeVariable, or if it should be just replaced by the mapping
        Returns:
        Type
      • array

        public static Type array​(Type componentType)
        Gets the array type—which might be a Class or a GenericArrayType depending on the argument—corresponding to the given element type.

        For example, arrayType(double.class) returns double[].class.

        This is the opposite of component(Type).

        Parameters:
        componentType - The type of elements which the array possesses
        See Also:
        component(java.lang.reflect.Type)
      • parameterize

        public static ParameterizedType parameterize​(Class<?> raw,
                                                     Type... typeArgs)
        Creates a new ParameterizedType of the given class together with the specified type arguments.
        Parameters:
        raw - The class of the ParameterizedType.
        typeArgs - The type arguments to use in parameterizing it, or an empty array to use the class's type variables with default bounds.
        Returns:
        The newly created ParameterizedType.
      • parameterize

        public static ParameterizedType parameterize​(Class<?> raw,
                                                     Map<TypeVariable<?>,​Type> typeVarAssigns)
        Create a parameterized type instance.
        Parameters:
        raw - the raw class to create a parameterized type instance for
        typeVarAssigns - the mapping used for parameterization
        Returns:
        ParameterizedType
      • wildcard

        public static WildcardType wildcard​(Type[] upperBounds,
                                            Type[] lowerBounds)
        Creates a new WildcardType with the given upper and/or lower bounds.
        Parameters:
        upperBounds - Upper bounds of the wildcard, or null for none.
        lowerBounds - Lower bounds of the wildcard, or null for none.
        Returns:
        The newly created WildcardType.