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.

    All three of these libraries contain fantastic generics-related logic, but none of the three contained everything that SciJava needed for all its use cases. Hence, we have drawn from sources as needed to create a unified generics API for use from SciJava applications. See in particular the SciJava Ops project, which utilizes these functions heavily.

    NB: The org.apache.commons.reflect.TypeUtils class of Apache Commons Lang version 3.4 is forked internally within this class. We did this for two reasons: 1) to avoid bringing in the whole of Apache Commons Lang as a dependency; and 2) to fix an infinite recursion bug in the TypeUtils.toString(Type) method.

    Author:
    Curtis Rueden, Gabe Selzer
    • Method Detail

      • load

        public static Class<?> load​(String name)
        Loads the class with the given name, using the current thread's context class loader, or null if it cannot be loaded.
        Parameters:
        name - The name of the class to load.
        Returns:
        The loaded class, or null if the class could not be loaded.
        See Also:
        load(String, ClassLoader, boolean)
      • load

        public static Class<?> load​(String name,
                                    ClassLoader classLoader)
        Loads the class with the given name, using the specified ClassLoader, or null if it cannot be loaded.
        Parameters:
        name - The name of the class to load.
        classLoader - The class loader with which to load the class; if null, the current thread's context class loader will be used.
        Returns:
        The loaded class, or null if the class could not be loaded.
        See Also:
        load(String, ClassLoader, boolean)
      • load

        public static Class<?> load​(String className,
                                    boolean quietly)
        Loads the class with the given name, using the current thread's context class loader.
        Parameters:
        className - the name of the class to load.
        quietly - Whether to return null (rather than throwing IllegalArgumentException) if something goes wrong loading the class.
        Returns:
        The loaded class, or null if the class could not be loaded and the quietly flag is set.
        Throws:
        IllegalArgumentException - If the class cannot be loaded and the quietly flag is not set.
        See Also:
        load(String, ClassLoader, boolean)
      • load

        public static Class<?> load​(String name,
                                    ClassLoader classLoader,
                                    boolean quietly)
        Loads the class with the given name, using the specified ClassLoader, or null if it cannot be loaded.

        This method is capable of parsing several different class name syntaxes. In particular, array classes (including primitives) represented using either square brackets or internal Java array name syntax are supported. Examples:

        • boolean is loaded as boolean.class
        • Z is loaded as boolean.class
        • double[] is loaded as double[].class
        • string[] is loaded as java.lang.String.class
        • [F is loaded as float[].class
        Parameters:
        name - The name of the class to load.
        classLoader - The class loader with which to load the class; if null, the current thread's context class loader will be used.
        quietly - Whether to return null (rather than throwing IllegalArgumentException) if something goes wrong loading the class
        Returns:
        The loaded class, or null if the class could not be loaded and the quietly flag is set.
        Throws:
        IllegalArgumentException - If the class cannot be loaded and the quietly flag is not set.
      • location

        public static URL location​(Class<?> c)
        Gets the base location of the given class.
        Parameters:
        c - The class whose location is desired.
        Returns:
        URL pointing to the class, or null if the location could not be determined.
        See Also:
        location(Class, boolean)
      • location

        public static URL location​(Class<?> c,
                                   boolean quietly)
        Gets the base location of the given class.

        If the class is directly on the file system (e.g., "/path/to/my/package/MyClass.class") then it will return the base directory (e.g., "file:/path/to").

        If the class is within a JAR file (e.g., "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the path to the JAR (e.g., "file:/path/to/my-jar.jar").

        Parameters:
        c - The class whose location is desired.
        quietly - Whether to return null (rather than throwing IllegalArgumentException) if something goes wrong determining the location.
        Returns:
        URL pointing to the class, or null if the location could not be determined and the quietly flag is set.
        Throws:
        IllegalArgumentException - If the location cannot be determined and the quietly flag is not set.
        See Also:
        to convert the result to a .
      • 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.
      • 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)
      • isBoolean

        public static boolean isBoolean​(Class<?> type)
      • isByte

        public static boolean isByte​(Class<?> type)
      • isCharacter

        public static boolean isCharacter​(Class<?> type)
      • isDouble

        public static boolean isDouble​(Class<?> type)
      • isFloat

        public static boolean isFloat​(Class<?> type)
      • isInteger

        public static boolean isInteger​(Class<?> type)
      • isLong

        public static boolean isLong​(Class<?> type)
      • isShort

        public static boolean isShort​(Class<?> type)
      • isNumber

        public static boolean isNumber​(Class<?> type)
      • isText

        public static boolean isText​(Class<?> type)
      • box

        public static <T> Class<T> box​(Class<T> type)
        Returns the non-primitive Class closest to the given type.

        Specifically, the following type conversions are done:

        • boolean.class becomes Boolean.class
        • byte.class becomes Byte.class
        • char.class becomes Character.class
        • double.class becomes Double.class
        • float.class becomes Float.class
        • int.class becomes Integer.class
        • long.class becomes Long.class
        • short.class becomes Short.class
        • void.class becomes Void.class

        All other types are unchanged.

      • unbox

        public static <T> Class<T> unbox​(Class<T> type)
        Returns the primitive Class closest to the given type.

        Specifically, the following type conversions are done:

        • Boolean.class becomes boolean.class
        • Byte.class becomes byte.class
        • Character.class becomes char.class
        • Double.class becomes double.class
        • Float.class becomes float.class
        • Integer.class becomes int.class
        • Long.class becomes long.class
        • Short.class becomes short.class
        • Void.class becomes void.class

        All other types are unchanged.

      • nullValue

        public static <T> T nullValue​(Class<T> type)
        Gets the "null" value for the given type. For non-primitives, this will actually be null. For primitives, it will be zero for numeric types, false for boolean, and the null character for char.
      • field

        public static Field field​(Class<?> c,
                                  String name)
        Gets the field with the specified name, of the given class, or superclass thereof.

        Unlike Class.getField(String), this method will return fields of any visibility, not just public. And unlike Class.getDeclaredField(String), it will do so recursively, returning the first field of the given name from the class's superclass hierarchy.

        Note that this method does not guarantee that the returned field is accessible; if the field is not public, calling code will need to use AccessibleObject.setAccessible(boolean) in order to manipulate the field's contents.

        Parameters:
        c - The class (or subclass thereof) containing the desired field.
        name -
        Returns:
        The first field with the given name in the class's superclass hierarchy.
        Throws:
        IllegalArgumentException - if the specified class does not contain a method with the given name
      • method

        public static Method method​(Class<?> c,
                                    String name,
                                    Class<?>... parameterTypes)
        Gets the method with the specified name and argument types, of the given class, or superclass thereof.

        Unlike Class.getMethod(String, Class[]), this method will return methods of any visibility, not just public. And unlike Class.getDeclaredMethod(String, Class[]), it will do so recursively, returning the first method of the given name and argument types from the class's superclass hierarchy.

        Note that this method does not guarantee that the returned method is accessible; if the method is not public, calling code will need to use AccessibleObject.setAccessible(boolean) in order to invoke the method.

        Parameters:
        c - The class (or subclass thereof) containing the desired method.
        name - Name of the method.
        parameterTypes - Types of the method parameters.
        Returns:
        The first method with the given name and argument types in the class's superclass hierarchy.
        Throws:
        IllegalArgumentException - If the specified class does not contain a method with the given name and argument types.
      • array

        public static Class<?> array​(Class<?> componentType)
        Gets the array class corresponding to the given element type.

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

        Parameters:
        componentType - The type of elements which the array possesses
        Throws:
        IllegalArgumentException - if the type cannot be the component type of an array (this is the case e.g. for void.class).
      • array

        public static Class<?> array​(Class<?> componentType,
                                     int dim)
        Gets the array class corresponding to the given element type and dimensionality.

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

        Parameters:
        componentType - The type of elements which the array possesses
        dim - The dimensionality of the array
      • 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 .

        Parameters:
        componentType - The type of elements which the array possesses
        See Also:
        component(java.lang.reflect.Type)
      • 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).

      • fieldType

        public static Type fieldType​(Field field,
                                     Class<?> type)
        Returns the "safe" 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 = Types.field(Thing.class, "thing");
        
         field.getType(); // Object
         field.getGenericType(); // T
        
         Types.fieldType(field, Thing.class); // T
         Types.fieldType(field, NumberThing.class); // N extends Number
         Types.fieldType(field, IntegerThing.class); // Integer
         
      • param

        public static Type param​(Type type,
                                 Class<?> c,
                                 int no)
        Gets the given type's nth type parameter of the specified class.

        For example, with class StringList implements List<String>, Types.param(StringList.class, Collection.class, 0) returns String.

      • 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)
      • 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. For example, enumValue("APPLE", Fruit.class) returns Fruit.APPLE if such a value is among those of the requested enum class.
        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.
      • enumFromLabel

        public static <T> T enumFromLabel​(String label,
                                          Class<T> dest)
        Converts the given string label to an enumeration constant of the specified type. An enum label is the string returned by the enum constant's Object.toString() method. For example, enumFromLabel("Apple", Fruit.class) returns Fruit.APPLE if Fruit.APPLE.toString() is implemented to return "Apple".
        Parameters:
        label - The toString() result of the desired enum value.
        dest - The type of the enumeration constant.
        Returns:
        The matching enumeration constant.
        Throws:
        IllegalArgumentException - if the type is not an enumeration type, or has no constant with the given label.
      • enumFromString

        public static <T> T enumFromString​(String s,
                                           Class<T> dest)
        Converts the given string value or label to an enumeration constant of the specified type.

        If the string matches one of the enum values directly, that value will be returned via enumValue(String, Class). Otherwise, the result of enumFromLabel(java.lang.String, java.lang.Class<T>) is returned.

        Parameters:
        s - The name or label of the desired enum value.
        dest - The type of the enumeration constant.
        Returns:
        The matching enumeration constant.
        Throws:
        IllegalArgumentException - if the type is not an enumeration type, or has no such constant with the given name nor label.
      • parameterizeWithOwner

        public static ParameterizedType parameterizeWithOwner​(Type ownerType,
                                                              Class<?> rawType,
                                                              Type... typeArgs)
        Creates a new ParameterizedType of the given class together with the specified type arguments.
        Parameters:
        ownerType - The owner type of the parameterized class.
        rawType - The class of the ParameterizedType.
        typeArgs - The type arguments to use in parameterizing it.
        Returns:
        The newly created ParameterizedType.
      • wildcard

        public static WildcardType wildcard​(Type upperBound,
                                            Type lowerBound)
        Creates a new WildcardType with the given upper and/or lower bound.
        Parameters:
        upperBound - Upper bound of the wildcard, or null for none.
        lowerBound - Lower bound of the wildcard, or null for none.
        Returns:
        The newly created WildcardType.
      • 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.
      • 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
      • args

        public static Map<TypeVariable<?>,​Type> args​(Type type,
                                                           Class<?> toClass)
        Gets the type arguments of a class/interface based on a subtype. For instance, this method will determine that both of the parameters for the interface Map are Object for the subtype Properties even though the subtype does not directly implement the Map interface.

        This method returns null if type is not assignable to toClass. It returns an empty map if none of the classes or interfaces in its inheritance hierarchy specify any type arguments.

        A side effect of this method is that it also retrieves the type arguments for the classes and interfaces that are part of the hierarchy between type and toClass. So with the above example, this method will also determine that the type arguments for Hashtable are also both Object. In cases where the interface specified by toClass is (indirectly) implemented more than once (e.g. where toClass specifies the interface Iterable and type specifies a parameterized type that implements both Set and Collection), this method will look at the inheritance hierarchy of only one of the implementations/subclasses; the first interface encountered that isn't a subinterface to one of the others in the type to toClass hierarchy.

        Parameters:
        type - the type from which to determine the type parameters of toClass
        toClass - the class whose type parameters are to be determined based on the subtype type
        Returns:
        a Map of the type assignments for the type variables in each type in the inheritance hierarchy from type to toClass inclusive.
      • args

        public static Map<TypeVariable<?>,​Type> args​(Class<?> c,
                                                           ParameterizedType superType)
        Tries to determine the type arguments of a class/interface based on a super parameterized type's type arguments. This method is the inverse of args(Type, Class) which gets a class/interface's type arguments based on a subtype. It is far more limited in determining the type arguments for the subject class's type variables in that it can only determine those parameters that map from the subject Class object to the supertype.

        Example: TreeSet sets its parameter as the parameter for NavigableSet, which in turn sets the parameter of SortedSet, which in turn sets the parameter of Set, which in turn sets the parameter of Collection, which in turn sets the parameter of Iterable. Since TreeSet's parameter maps (indirectly) to Iterable's parameter, it will be able to determine that based on the super type Iterable<? extends Map<Integer, ? extends Collection<?>>>, the parameter of TreeSet is ? extends Map<Integer, ? extends Collection<?>>.

        Parameters:
        c - the class whose type parameters are to be determined, not null
        superType - the super type from which c's type arguments are to be determined, not null
        Returns:
        a Map of the type assignments that could be determined for the type variables in each type in the inheritance hierarchy from type to c inclusive.
      • parameterize

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