- java.lang.Object
-
- org.scijava.common3.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.reflectpackage. - Apache Commons Lang 3's
org.apache.commons.lang3.reflectpackage. - GenTyRef (Generic Type Reflector), a library for runtime generic type introspection.
- Author:
- Curtis Rueden, Gabriel Selzer, David Kolb
- Google Guava's
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static Typearray(Type componentType)Gets the array type—which might be aClassor aGenericArrayTypedepending on the argument—corresponding to the given element type.static <T> Tcast(Object src, Class<T> dest)Casts the given object to the specified type, or null if the types are incompatible.static TypecommonSuperTypeOf(Type... types)Determines the greatest common supertype of all types in the input array.static Typecomponent(Type type)Gets the component type of the given array type, or null if not an array.static booleancontainsTypeVars(Type type)Learn, recursively, whether any of the type parameters associated withtypeare bound to variables.static <T> TenumValue(String name, Class<T> dest)Converts the given string value to an enumeration constant of the specified type.static booleanisAssignable(Type source, Type target)Discerns whether it would be legal to assign a reference of typesourceto a reference of typetarget.static booleanisAssignable(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.static booleanisInstance(Object obj, Class<?> dest)Checks whether the given object can be cast to the specified type.static booleanisRecursive(Type type)Checks if the givenTypeis recursively typed: that is if it's aParameterizedTypewith a self-referential type parameter.static booleanisRecursiveBound(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, iftypeBounditself has a type argument equal torefType.static Stringname(Type t)Gets a string representation of the given type.static ParameterizedTypeparameterize(Class<?> raw, Type... typeArgs)Creates a newParameterizedTypeof the given class together with the specified type arguments.static ParameterizedTypeparameterize(Class<?> raw, Map<TypeVariable<?>,Type> typeVarAssigns)Create a parameterized type instance.static Type[]paramTypesOf(Method m, Type type)Returns the exact parameter types of the given method in the given type.static Class<?>raw(Type type)Gets the (first) raw class of the given type.static List<Class<?>>raws(Type type)Gets all raw classes corresponding to the given type.static TypereturnTypeOf(Method m, Type type)Returns the exact return type of the given method in the given type.static TypesuperTypeOf(Type type, Class<?> searchClass)Finds the most specific supertype oftypewhose erasure issearchClass.static TypetypeOf(Field field, Class<?> type)Returns the exact generic type of the given field, as viewed from the given type.static Type[]typeParamsOf(Type src, Class<?> superclass)static Type[]unroll(Type[] typesToMap, Map<TypeVariable<?>,Type> typeVarAssigns)Map type vars in specified type list to types using the specified map.static Typeunroll(Type typeToMap, Map<TypeVariable<?>,Type> typeVarAssigns)Map type vars in the specified type to a type using the specified map.static Typeunroll(Map<TypeVariable<?>,Type> typeVarAssigns, Type type, boolean followTypeVars)Get a type representingtypewith variable assignments "unrolled."static booleanvarsSatisfied(Map<TypeVariable<?>,Type> typeVarAssigns)Determines whether or not specified types satisfy the bounds of their mapped type variables.static WildcardTypewildcard(Type... upperBounds)Creates a newWildcardTypewith the given upper bound(s).static WildcardTypewildcard(Type[] upperBounds, Type[] lowerBounds)Creates a newWildcardTypewith the given upper and/or lower bounds.
-
-
-
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
Classitself, 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.
- If the type is a
-
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 & Iterablewill return bothNumberandIterableas 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 whatField.getGenericType()returns, if the field is declared in a superclass, ortypehas 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 fromm.getGenericParameterTypes()when the method was declared in a superclass, ortypehas a type parameter that is used in one of the parameters, ortypeis 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 fromm.getGenericReturnType()when the method was declared in a superclass, ortypehas a type parameter that is used in the return type, ortypeis 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 typesourceto a reference of typetarget.- 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- iftargetis 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 typetoType- the target typetypeVarAssigns- optional map of type variable assignments- Returns:
trueiftypeis assignable totoType.
-
superTypeOf
public static Type superTypeOf(Type type, Class<?> searchClass)
Finds the most specific supertype oftypewhose erasure issearchClass. In other words, returns a type representing the classsearchClassplus its exact type parameters intype.- Returns an instance of
ParameterizedTypeifsearchClassis a real class or interface andtypehas parameters for it - Returns an instance of
GenericArrayTypeifsearchClassis an array type, andtypehas type parameters for it - Returns an instance of
Classiftypeis a raw type, or has no type parameters forsearchClass - Returns null if
searchClassis not a superclass of type.
For example, with
class StringList implements List<String>,superTypeOf(StringList.class, Collection.class)returns aParameterizedTyperepresentingCollection<String>.- Parameters:
type-searchClass-
- Returns an instance of
-
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).
-
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 callClass.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 ofTypesrcwith respect to theClassdest. Whensrchas no type parameters (or is not a subclass ofdest), an empty array is returned.- Parameters:
src- - theTypewhose type parameters will be returned.superclass- - theClassagainst which we want the type parameters ofsrc- Returns:
- an array of
Types denoting the type
-
containsTypeVars
public static boolean containsTypeVars(Type type)
Learn, recursively, whether any of the type parameters associated withtypeare bound to variables.- Parameters:
type- the type to check for type variables- Returns:
- boolean
-
isRecursive
public static boolean isRecursive(Type type)
Checks if the givenTypeis recursively typed: that is if it's aParameterizedTypewith a self-referential type parameter.- Parameters:
type- Type of interest to interrogate- Returns:
Trueif the given type is recursively parameterized,Falseotherwise
-
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, iftypeBounditself has a type argument equal torefType.- Parameters:
refType- Base type to checktypeBound- A bound ofrefType- Returns:
- True if
typeBoundis parameterized with a type argument that is itself equal torefType
-
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 intypeVarAssigns.- Parameters:
typeVarAssigns- specifies the potential types to be assigned to the type variables, notnull.- 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 representingtypewith variable assignments "unrolled."- Parameters:
typeVarAssigns- aMapof the type assignments for the type variables in each type in the inheritance hierarchy oftype.type- the type to unroll variable assignments forfollowTypeVars- whether aTypeVariableshould be recursively followed if it maps to anotherTypeVariable, 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 aClassor aGenericArrayTypedepending on the argument—corresponding to the given element type.For example,
arrayType(double.class)returnsdouble[].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 newParameterizedTypeof the given class together with the specified type arguments.- Parameters:
raw- The class of theParameterizedType.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 fortypeVarAssigns- the mapping used for parameterization- Returns:
ParameterizedType
-
wildcard
public static WildcardType wildcard(Type... upperBounds)
Creates a newWildcardTypewith the given upper bound(s).- Returns:
- The newly created
WildcardType.
-
wildcard
public static WildcardType wildcard(Type[] upperBounds, Type[] lowerBounds)
Creates a newWildcardTypewith 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.
-
-