Class ReflectionUtils
- java.lang.Object
-
- org.junit.platform.commons.util.ReflectionUtils
-
@API(status=INTERNAL, since="1.0") public final class ReflectionUtils extends Object
Collection of utilities for working with the Java reflection APIs.DISCLAIMER
These utilities are intended solely for usage within the JUnit framework itself. Any usage by external parties is not supported. Use at your own risk!
Some utilities are published via the maintained
ReflectionSupportclass.- Since:
- 1.0
- See Also:
ReflectionSupport
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classReflectionUtils.HierarchyTraversalModeModes in which a hierarchy can be traversed — for example, when searching for methods or fields within a class hierarchy.
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static List<Class<?>>findAllClassesInClasspathRoot(URI root, Predicate<Class<?>> classFilter, Predicate<String> classNameFilter)static List<Class<?>>findAllClassesInClasspathRoot(URI root, ClassFilter classFilter)static List<Class<?>>findAllClassesInModule(String moduleName, Predicate<Class<?>> classFilter, Predicate<String> classNameFilter)static List<Class<?>>findAllClassesInModule(String moduleName, ClassFilter classFilter)static List<Class<?>>findAllClassesInPackage(String basePackageName, Predicate<Class<?>> classFilter, Predicate<String> classNameFilter)static List<Class<?>>findAllClassesInPackage(String basePackageName, ClassFilter classFilter)static List<Constructor<?>>findConstructors(Class<?> clazz, Predicate<Constructor<?>> predicate)Find all constructors in the supplied class that match the supplied predicate.static List<Field>findFields(Class<?> clazz, Predicate<Field> predicate, ReflectionUtils.HierarchyTraversalMode traversalMode)static Optional<Method>findMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes)static Optional<Method>findMethod(Class<?> clazz, String methodName, String parameterTypeNames)static List<Method>findMethods(Class<?> clazz, Predicate<Method> predicate)Find all methods of the supplied class or interface that match the specifiedpredicate, using top-down search semantics within the type hierarchy.static List<Method>findMethods(Class<?> clazz, Predicate<Method> predicate, ReflectionUtils.HierarchyTraversalMode traversalMode)static List<Class<?>>findNestedClasses(Class<?> clazz, Predicate<Class<?>> predicate)static Set<Class<?>>getAllAssignmentCompatibleClasses(Class<?> clazz)Return all classes and interfaces that can be used as assignment types for instances of the specifiedClass, including itself.static Set<Path>getAllClasspathRootDirectories()static <T> Constructor<T>getDeclaredConstructor(Class<T> clazz)Get the sole declaredConstructorfor the supplied class.static StringgetFullyQualifiedMethodName(Class<?> clazz, Method method)Build the fully qualified method name for the method described by the supplied class and method.static StringgetFullyQualifiedMethodName(Class<?> clazz, String methodName, Class<?>... parameterTypes)Build the fully qualified method name for the method described by the supplied class, method name, and parameter types.static Optional<Object>getOutermostInstance(Object inner, Class<?> requiredType)Deprecated.static Class<?>getWrapperType(Class<?> type)Get the wrapper type for the supplied primitive type.static ObjectinvokeMethod(Method method, Object target, Object... args)static booleanisAbstract(Class<?> clazz)static booleanisAbstract(Member member)static booleanisArray(Object obj)Determine if the supplied object is an array.static booleanisAssignableTo(Object obj, Class<?> targetType)Determine if the supplied object can be assigned to the supplied target type for the purpose of reflective method invocations.static booleanisFinal(Class<?> clazz)static booleanisFinal(Member member)static booleanisInnerClass(Class<?> clazz)Determine if the supplied class is an inner class (i.e., a non-static member class).static booleanisMethodPresent(Class<?> clazz, Predicate<Method> predicate)static booleanisMultidimensionalArray(Object obj)Determine if the supplied object is a multidimensional array.static booleanisNotFinal(Class<?> clazz)static booleanisNotFinal(Member member)static booleanisNotPrivate(Class<?> clazz)static booleanisNotPrivate(Member member)static booleanisNotStatic(Class<?> clazz)static booleanisNotStatic(Member member)static booleanisPrivate(Class<?> clazz)static booleanisPrivate(Member member)static booleanisPublic(Class<?> clazz)static booleanisPublic(Member member)static booleanisStatic(Class<?> clazz)static booleanisStatic(Member member)static Optional<Class<?>>loadClass(String name)Deprecated.Please usetryToLoadClass(String)instead.static Optional<Class<?>>loadClass(String name, ClassLoader classLoader)Deprecated.Please usetryToLoadClass(String, ClassLoader)instead.static <T extends AccessibleObject>
TmakeAccessible(T object)static <T> TnewInstance(Class<T> clazz, Object... args)static <T> TnewInstance(Constructor<T> constructor, Object... args)Create a new instance of typeTby invoking the supplied constructor with the supplied arguments.static String[]parseFullyQualifiedMethodName(String fullyQualifiedMethodName)Parse the supplied fully qualified method name into a 3-elementString[]with the following content.static <T> Optional<Object>readFieldValue(Class<T> clazz, String fieldName, T instance)Deprecated.Please usetryToReadFieldValue(Class, String, Object)instead.static Optional<Object>readFieldValue(Field field)Deprecated.Please usetryToReadFieldValue(Field)instead.static Optional<Object>readFieldValue(Field field, Object instance)Deprecated.Please usetryToReadFieldValue(Field, Object)instead.static List<Object>readFieldValues(List<Field> fields, Object instance)Read the values of the supplied fields, making each field accessible if necessary and masking any checked exception as an unchecked exception.static List<Object>readFieldValues(List<Field> fields, Object instance, Predicate<Field> predicate)Read the values of the supplied fields, making each field accessible if necessary, masking any checked exception as an unchecked exception, and filtering out fields that do not pass the suppliedpredicate.static booleanreturnsVoid(Method method)static Try<Method>tryToGetMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes)Try to get theMethodin the specified class with the specified name and parameter types.static Try<Class<?>>tryToLoadClass(String name)static Try<Class<?>>tryToLoadClass(String name, ClassLoader classLoader)Try to load a class by its primitive name or fully qualified name, using the suppliedClassLoader.static <T> Try<Object>tryToReadFieldValue(Class<T> clazz, String fieldName, T instance)Try to read the value of a potentially inaccessible or nonexistent field.static Try<Object>tryToReadFieldValue(Field field)Try to read the value of a potentially inaccessible static field.static Try<Object>tryToReadFieldValue(Field field, Object instance)
-
-
-
Method Detail
-
isPublic
public static boolean isPublic(Class<?> clazz)
-
isPublic
public static boolean isPublic(Member member)
-
isPrivate
public static boolean isPrivate(Class<?> clazz)
-
isPrivate
public static boolean isPrivate(Member member)
-
isAbstract
public static boolean isAbstract(Class<?> clazz)
-
isAbstract
public static boolean isAbstract(Member member)
-
isStatic
public static boolean isStatic(Class<?> clazz)
-
isStatic
public static boolean isStatic(Member member)
-
isFinal
@API(status=INTERNAL, since="1.5") public static boolean isFinal(Class<?> clazz)
- Since:
- 1.5
-
isNotFinal
@API(status=INTERNAL, since="1.5") public static boolean isNotFinal(Class<?> clazz)
- Since:
- 1.5
-
isNotFinal
@API(status=INTERNAL, since="1.5") public static boolean isNotFinal(Member member)
- Since:
- 1.5
-
isInnerClass
public static boolean isInnerClass(Class<?> clazz)
Determine if the supplied class is an inner class (i.e., a non-static member class).Technically speaking (i.e., according to the Java Language Specification), "an inner class may be a non-static member class, a local class, or an anonymous class." However, this method does not return
truefor a local or anonymous class.- Parameters:
clazz- the class to check; nevernull- Returns:
trueif the class is an inner class
-
returnsVoid
public static boolean returnsVoid(Method method)
-
isArray
public static boolean isArray(Object obj)
Determine if the supplied object is an array.- Parameters:
obj- the object to test; potentiallynull- Returns:
trueif the object is an array
-
isMultidimensionalArray
@API(status=INTERNAL, since="1.3.2") public static boolean isMultidimensionalArray(Object obj)
Determine if the supplied object is a multidimensional array.- Parameters:
obj- the object to test; potentiallynull- Returns:
trueif the object is a multidimensional array- Since:
- 1.3.2
-
isAssignableTo
public static boolean isAssignableTo(Object obj, Class<?> targetType)
Determine if the supplied object can be assigned to the supplied target type for the purpose of reflective method invocations.In contrast to
Class.isInstance(Object), this method returnstrueif the target type represents a primitive type whose wrapper matches the supplied object's type. In addition, this method also supports widening conversions for primitive types and their corresponding wrapper types.If the supplied object is
nulland the supplied type does not represent a primitive type, this method returnstrue.- Parameters:
obj- the object to test for assignment compatibility; potentiallynulltargetType- the type to check against; nevernull- Returns:
trueif the object is assignment compatible- See Also:
Class.isInstance(Object),Class.isAssignableFrom(Class)
-
getWrapperType
public static Class<?> getWrapperType(Class<?> type)
Get the wrapper type for the supplied primitive type.- Parameters:
type- the primitive type for which to retrieve the wrapper type- Returns:
- the corresponding wrapper type or
nullif the supplied type isnullor not a primitive type
-
newInstance
public static <T> T newInstance(Constructor<T> constructor, Object... args)
Create a new instance of typeTby invoking the supplied constructor with the supplied arguments.The constructor will be made accessible if necessary, and any checked exception will be masked as an unchecked exception.
- Parameters:
constructor- the constructor to invoke; nevernullargs- the arguments to pass to the constructor- Returns:
- the new instance; never
null - See Also:
newInstance(Class, Object...),ExceptionUtils.throwAsUncheckedException(Throwable)
-
readFieldValue
@API(status=DEPRECATED, since="1.4") @Deprecated public static <T> Optional<Object> readFieldValue(Class<T> clazz, String fieldName, T instance)
Deprecated.Please usetryToReadFieldValue(Class, String, Object)instead.Read the value of a potentially inaccessible or nonexistent field.If the field does not exist or the value of the field is
null, an emptyOptionalwill be returned.- Parameters:
clazz- the class where the field is declared; nevernullfieldName- the name of the field; nevernullor emptyinstance- the instance from where the value is to be read; may benullfor a static field- See Also:
readFieldValue(Field),readFieldValue(Field, Object)
-
tryToReadFieldValue
@API(status=INTERNAL, since="1.4") public static <T> Try<Object> tryToReadFieldValue(Class<T> clazz, String fieldName, T instance)
Try to read the value of a potentially inaccessible or nonexistent field.If the field does not exist or an exception occurs while reading it, a failed
Tryis returned that contains the corresponding exception.- Parameters:
clazz- the class where the field is declared; nevernullfieldName- the name of the field; nevernullor emptyinstance- the instance from where the value is to be read; may benullfor a static field- Since:
- 1.4
- See Also:
tryToReadFieldValue(Field),tryToReadFieldValue(Field, Object)
-
readFieldValue
@API(status=DEPRECATED, since="1.4") @Deprecated public static Optional<Object> readFieldValue(Field field)
Deprecated.Please usetryToReadFieldValue(Field)instead.Read the value of the supplied static field, making it accessible if necessary and masking any checked exception as an unchecked exception.If the value of the field is
null, an emptyOptionalwill be returned.- Parameters:
field- the field to read; nevernull- See Also:
readFieldValue(Field, Object),readFieldValue(Class, String, Object)
-
tryToReadFieldValue
@API(status=INTERNAL, since="1.4") public static Try<Object> tryToReadFieldValue(Field field)
Try to read the value of a potentially inaccessible static field.If an exception occurs while reading the field, a failed
Tryis returned that contains the corresponding exception.- Parameters:
field- the field to read; nevernull- Since:
- 1.4
- See Also:
tryToReadFieldValue(Field, Object),tryToReadFieldValue(Class, String, Object)
-
readFieldValue
@API(status=DEPRECATED, since="1.4") @Deprecated public static Optional<Object> readFieldValue(Field field, Object instance)
Deprecated.Please usetryToReadFieldValue(Field, Object)instead.Read the value of the supplied field, making it accessible if necessary and masking any checked exception as an unchecked exception.If the value of the field is
null, an emptyOptionalwill be returned.- Parameters:
field- the field to read; nevernullinstance- the instance from which the value is to be read; may benullfor a static field- See Also:
readFieldValue(Field),readFieldValue(Class, String, Object)
-
tryToReadFieldValue
@API(status=INTERNAL, since="1.4") public static Try<Object> tryToReadFieldValue(Field field, Object instance)
-
readFieldValues
public static List<Object> readFieldValues(List<Field> fields, Object instance)
Read the values of the supplied fields, making each field accessible if necessary and masking any checked exception as an unchecked exception.- Parameters:
fields- the list of fields to read; nevernullinstance- the instance from which the values are to be read; may benullfor static fields- Returns:
- an immutable list of the values of the specified fields; never
nullbut may be empty or containnullentries
-
readFieldValues
public static List<Object> readFieldValues(List<Field> fields, Object instance, Predicate<Field> predicate)
Read the values of the supplied fields, making each field accessible if necessary, masking any checked exception as an unchecked exception, and filtering out fields that do not pass the suppliedpredicate.- Parameters:
fields- the list of fields to read; nevernullinstance- the instance from which the values are to be read; may benullfor static fieldspredicate- the field filter; nevernull- Returns:
- an immutable list of the values of the specified fields; never
nullbut may be empty or containnullentries
-
loadClass
@API(status=DEPRECATED, since="1.4") @Deprecated public static Optional<Class<?>> loadClass(String name)
Deprecated.Please usetryToLoadClass(String)instead.- See Also:
ReflectionSupport.loadClass(String)
-
tryToLoadClass
@API(status=INTERNAL, since="1.4") public static Try<Class<?>> tryToLoadClass(String name)
- Since:
- 1.4
- See Also:
ReflectionSupport.tryToLoadClass(String)
-
loadClass
@API(status=DEPRECATED, since="1.4") @Deprecated public static Optional<Class<?>> loadClass(String name, ClassLoader classLoader)
Deprecated.Please usetryToLoadClass(String, ClassLoader)instead.Load a class by its primitive name or fully qualified name, using the suppliedClassLoader.See
ReflectionSupport.loadClass(String)for details on support for class names for arrays.- Parameters:
name- the name of the class to load; nevernullor blankclassLoader- theClassLoaderto use; nevernull- See Also:
loadClass(String)
-
tryToLoadClass
@API(status=INTERNAL, since="1.4") public static Try<Class<?>> tryToLoadClass(String name, ClassLoader classLoader)
Try to load a class by its primitive name or fully qualified name, using the suppliedClassLoader.See
ReflectionSupport.tryToLoadClass(String)for details on support for class names for arrays.- Parameters:
name- the name of the class to load; nevernullor blankclassLoader- theClassLoaderto use; nevernull- Since:
- 1.4
- See Also:
tryToLoadClass(String)
-
getFullyQualifiedMethodName
public static String getFullyQualifiedMethodName(Class<?> clazz, Method method)
Build the fully qualified method name for the method described by the supplied class and method.Note that the class is not necessarily the class in which the method is declared.
- Parameters:
clazz- the class from which the method should be referenced; nevernullmethod- the method; nevernull- Returns:
- fully qualified method name; never
null - Since:
- 1.4
- See Also:
getFullyQualifiedMethodName(Class, String, Class...)
-
getFullyQualifiedMethodName
public static String getFullyQualifiedMethodName(Class<?> clazz, String methodName, Class<?>... parameterTypes)
Build the fully qualified method name for the method described by the supplied class, method name, and parameter types.Note that the class is not necessarily the class in which the method is declared.
- Parameters:
clazz- the class from which the method should be referenced; nevernullmethodName- the name of the method; nevernullor blankparameterTypes- the parameter types of the method; may benullor empty- Returns:
- fully qualified method name; never
null - See Also:
getFullyQualifiedMethodName(Class, Method)
-
parseFullyQualifiedMethodName
public static String[] parseFullyQualifiedMethodName(String fullyQualifiedMethodName)
Parse the supplied fully qualified method name into a 3-elementString[]with the following content.- index
0: the fully qualified class name - index
1: the name of the method - index
2: a comma-separated list of parameter types, or a blank string if the method does not declare any formal parameters
- Parameters:
fullyQualifiedMethodName- a fully qualified method name, nevernullor blank- Returns:
- a 3-element array of strings containing the parsed values
- index
-
getOutermostInstance
@API(status=DEPRECATED, since="1.4") @Deprecated public static Optional<Object> getOutermostInstance(Object inner, Class<?> requiredType)
Deprecated.Get the outermost instance of the required type, searching recursively through enclosing instances.If the supplied inner object is of the required type, it will simply be returned.
- Parameters:
inner- the inner object from which to begin the search; nevernullrequiredType- the required type of the outermost instance; nevernull- Returns:
- an
Optionalcontaining the outermost instance; nevernullbut potentially empty
-
findAllClassesInClasspathRoot
public static List<Class<?>> findAllClassesInClasspathRoot(URI root, Predicate<Class<?>> classFilter, Predicate<String> classNameFilter)
-
findAllClassesInClasspathRoot
public static List<Class<?>> findAllClassesInClasspathRoot(URI root, ClassFilter classFilter)
- Since:
- 1.1
-
findAllClassesInPackage
public static List<Class<?>> findAllClassesInPackage(String basePackageName, Predicate<Class<?>> classFilter, Predicate<String> classNameFilter)
-
findAllClassesInPackage
public static List<Class<?>> findAllClassesInPackage(String basePackageName, ClassFilter classFilter)
- Since:
- 1.1
-
findAllClassesInModule
public static List<Class<?>> findAllClassesInModule(String moduleName, Predicate<Class<?>> classFilter, Predicate<String> classNameFilter)
- Since:
- 1.1.1
- See Also:
ReflectionSupport.findAllClassesInModule(String, Predicate, Predicate)
-
findAllClassesInModule
public static List<Class<?>> findAllClassesInModule(String moduleName, ClassFilter classFilter)
- Since:
- 1.1.1
-
findNestedClasses
public static List<Class<?>> findNestedClasses(Class<?> clazz, Predicate<Class<?>> predicate)
-
getDeclaredConstructor
public static <T> Constructor<T> getDeclaredConstructor(Class<T> clazz)
Get the sole declaredConstructorfor the supplied class.Throws a
PreconditionViolationExceptionif the supplied class declares more than one constructor.- Parameters:
clazz- the class to get the constructor for- Returns:
- the sole declared constructor; never
null - See Also:
Class.getDeclaredConstructors()
-
findConstructors
public static List<Constructor<?>> findConstructors(Class<?> clazz, Predicate<Constructor<?>> predicate)
Find all constructors in the supplied class that match the supplied predicate.- Parameters:
clazz- the class in which to search for constructors; nevernullpredicate- the predicate to use to test for a match; nevernull- Returns:
- an immutable list of all such constructors found; never
nullbut potentially empty
-
findFields
public static List<Field> findFields(Class<?> clazz, Predicate<Field> predicate, ReflectionUtils.HierarchyTraversalMode traversalMode)
-
isMethodPresent
public static boolean isMethodPresent(Class<?> clazz, Predicate<Method> predicate)
Determine if aMethodmatching the suppliedPredicateis present within the type hierarchy of the specified class, beginning with the specified class or interface and traversing up the type hierarchy until such a method is found or the type hierarchy is exhausted.- Parameters:
clazz- the class or interface in which to find the method; nevernullpredicate- the predicate to use to test for a match; nevernull- Returns:
trueif such a method is present- See Also:
findMethod(Class, String, String),findMethod(Class, String, Class...)
-
tryToGetMethod
@API(status=INTERNAL, since="1.4") public static Try<Method> tryToGetMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes)
Try to get theMethodin the specified class with the specified name and parameter types.This method delegates to
Class.getMethod(String, Class...)but catches any exception thrown.- Parameters:
clazz- the class in which to search for the method; nevernullmethodName- the name of the method to get; nevernullor blankparameterTypes- the parameter types of the method; may benullor empty- Returns:
- a successful
Trycontaining the method or a failedTrycontaining theNoSuchMethodExceptionthrown byClass#getMethod(); nevernull - Since:
- 1.4
-
findMethod
public static Optional<Method> findMethod(Class<?> clazz, String methodName, String parameterTypeNames)
-
findMethod
public static Optional<Method> findMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes)
-
findMethods
public static List<Method> findMethods(Class<?> clazz, Predicate<Method> predicate)
Find all methods of the supplied class or interface that match the specifiedpredicate, using top-down search semantics within the type hierarchy.The results will not contain instance methods that are overridden or
staticmethods that are hidden.- Parameters:
clazz- the class or interface in which to find the methods; nevernullpredicate- the method filter; nevernull- Returns:
- an immutable list of all such methods found; never
null - See Also:
ReflectionUtils.HierarchyTraversalMode.TOP_DOWN,findMethods(Class, Predicate, HierarchyTraversalMode)
-
findMethods
public static List<Method> findMethods(Class<?> clazz, Predicate<Method> predicate, ReflectionUtils.HierarchyTraversalMode traversalMode)
-
makeAccessible
public static <T extends AccessibleObject> T makeAccessible(T object)
-
getAllAssignmentCompatibleClasses
public static Set<Class<?>> getAllAssignmentCompatibleClasses(Class<?> clazz)
Return all classes and interfaces that can be used as assignment types for instances of the specifiedClass, including itself.- Parameters:
clazz- theClassto look up- See Also:
Class.isAssignableFrom(java.lang.Class<?>)
-
-