@API(status=INTERNAL,
since="1.0")
public final class ReflectionUtils
extends java.lang.Object
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 ReflectionSupport
class.
ReflectionSupport
Modifier and Type | Class and Description |
---|---|
static class |
ReflectionUtils.HierarchyTraversalMode
Modes in which a hierarchy can be traversed — for example, when
searching for methods or fields within a class hierarchy.
|
Modifier and Type | Field and Description |
---|---|
private static java.util.Map<java.lang.String,java.lang.Class<?>> |
classNameToTypeMap
Internal cache of common class names mapped to their types.
|
private static ClasspathScanner |
classpathScanner |
private static java.lang.Class<?>[] |
EMPTY_CLASS_ARRAY |
private static java.util.regex.Pattern |
FULLY_QUALIFIED_METHOD_NAME_PATTERN |
private static java.util.Map<java.lang.Class<?>,java.lang.Class<?>> |
primitiveToWrapperMap
Internal cache of primitive types mapped to their wrapper types.
|
private static java.util.regex.Pattern |
SOURCE_CODE_SYNTAX_ARRAY_PATTERN |
private static java.util.regex.Pattern |
VM_INTERNAL_OBJECT_ARRAY_PATTERN |
private static java.util.regex.Pattern |
VM_INTERNAL_PRIMITIVE_ARRAY_PATTERN
Pattern: "[x", "[[[[x", etc., where x is Z, B, C, D, F, I, J, S, etc.
|
Modifier | Constructor and Description |
---|---|
private |
ReflectionUtils() |
Modifier and Type | Method and Description |
---|---|
private static int |
defaultMethodSorter(java.lang.reflect.Method method1,
java.lang.reflect.Method method2)
Method comparator based upon JUnit 4's
org.junit.internal.MethodSorter
implementation. |
static java.util.List<java.lang.Class<?>> |
findAllClassesInClasspathRoot(java.net.URI root,
java.util.function.Predicate<java.lang.Class<?>> classTester,
java.util.function.Predicate<java.lang.String> classNameFilter) |
static java.util.List<java.lang.Class<?>> |
findAllClassesInPackage(java.lang.String basePackageName,
java.util.function.Predicate<java.lang.Class<?>> classTester,
java.util.function.Predicate<java.lang.String> classNameFilter) |
private static java.util.List<java.lang.reflect.Method> |
findAllMethodsInHierarchy(java.lang.Class<?> clazz,
ReflectionUtils.HierarchyTraversalMode traversalMode)
Find all non-synthetic methods in the superclass and interface hierarchy,
excluding Object.
|
private static java.util.Optional<java.lang.reflect.Method> |
findMethod(java.lang.Class<?> clazz,
java.util.function.Predicate<java.lang.reflect.Method> predicate) |
static java.util.Optional<java.lang.reflect.Method> |
findMethod(java.lang.Class<?> clazz,
java.lang.String methodName,
java.lang.Class<?>... parameterTypes) |
static java.util.Optional<java.lang.reflect.Method> |
findMethod(java.lang.Class<?> clazz,
java.lang.String methodName,
java.lang.String parameterTypeNames) |
static java.util.List<java.lang.reflect.Method> |
findMethods(java.lang.Class<?> clazz,
java.util.function.Predicate<java.lang.reflect.Method> predicate)
Find all methods of the supplied class or interface
that match the specified
predicate , using top-down search semantics
within the type hierarchy. |
static java.util.List<java.lang.reflect.Method> |
findMethods(java.lang.Class<?> clazz,
java.util.function.Predicate<java.lang.reflect.Method> predicate,
ReflectionUtils.HierarchyTraversalMode traversalMode) |
static java.util.List<java.lang.Class<?>> |
findNestedClasses(java.lang.Class<?> clazz,
java.util.function.Predicate<java.lang.Class<?>> predicate) |
private static void |
findNestedClasses(java.lang.Class<?> clazz,
java.util.Set<java.lang.Class<?>> candidates) |
static java.util.Set<java.lang.Class<?>> |
getAllAssignmentCompatibleClasses(java.lang.Class<?> clazz)
Return all classes and interfaces that can be used as assignment types
for instances of the specified
Class , including itself. |
private static void |
getAllAssignmentCompatibleClasses(java.lang.Class<?> clazz,
java.util.Set<java.lang.Class<?>> result) |
static java.util.Set<java.nio.file.Path> |
getAllClasspathRootDirectories() |
static <T> java.lang.reflect.Constructor<T> |
getDeclaredConstructor(java.lang.Class<T> clazz)
Get the sole declared
Constructor for the supplied class. |
private static java.util.List<java.lang.reflect.Method> |
getDeclaredMethods(java.lang.Class<?> clazz,
ReflectionUtils.HierarchyTraversalMode traversalMode)
Custom alternative to
Class.getDeclaredMethods() that sorts the
methods and converts them to a mutable list. |
private static java.util.List<java.lang.reflect.Method> |
getDefaultMethods(java.lang.Class<?> clazz)
Get a sorted, mutable list of all default methods present in interfaces
implemented by the supplied class which are also visible within
the supplied class.
|
static java.lang.String |
getFullyQualifiedMethodName(java.lang.Class<?> clazz,
java.lang.String methodName,
java.lang.Class<?>... parameterTypes)
Build the fully qualified method name for the method described by the
supplied class, method name, and parameter types.
|
private static java.util.List<java.lang.reflect.Method> |
getInterfaceMethods(java.lang.Class<?> clazz,
ReflectionUtils.HierarchyTraversalMode traversalMode) |
(package private) static java.util.Optional<java.lang.reflect.Method> |
getMethod(java.lang.Class<?> clazz,
java.lang.String methodName,
java.lang.Class<?>... parameterTypes)
Get the
Method in the specified class with the specified name
and parameter types. |
private static java.util.List<java.lang.reflect.Method> |
getMethods(java.lang.Class<?> clazz)
Custom alternative to
Class.getMethods() that sorts the methods
and converts them to a mutable list. |
private static java.util.Optional<java.lang.Object> |
getOuterInstance(java.lang.Object inner) |
static java.util.Optional<java.lang.Object> |
getOutermostInstance(java.lang.Object inner,
java.lang.Class<?> requiredType)
Get the outermost instance of the required type, searching recursively
through enclosing instances.
|
private static java.util.List<java.lang.reflect.Method> |
getSuperclassMethods(java.lang.Class<?> clazz,
ReflectionUtils.HierarchyTraversalMode traversalMode) |
private static java.lang.Throwable |
getUnderlyingCause(java.lang.Throwable t)
Get the underlying cause of the supplied
Throwable . |
static java.lang.Class<?> |
getWrapperType(java.lang.Class<?> type)
Get the wrapper type for the supplied primitive type.
|
private static boolean |
hasCompatibleSignature(java.lang.reflect.Method candidate,
java.lang.String methodName,
java.lang.Class<?>[] parameterTypes)
Determine if the supplied candidate method (typically a method higher in
the type hierarchy) has a signature that is compatible with a method that
has the supplied name and parameter types, taking method sub-signatures
and generics into account.
|
static java.lang.Object |
invokeMethod(java.lang.reflect.Method method,
java.lang.Object target,
java.lang.Object... args) |
static boolean |
isAbstract(java.lang.Class<?> clazz) |
static boolean |
isAbstract(java.lang.reflect.Member member) |
static boolean |
isArray(java.lang.Object obj)
Determine if the supplied object is an array.
|
static boolean |
isAssignableTo(java.lang.Object obj,
java.lang.Class<?> type)
Determine if the supplied object can be assigned to the supplied type
for the purpose of reflective method invocations.
|
(package private) static boolean |
isGeneric(java.lang.reflect.Method method) |
private static boolean |
isGeneric(java.lang.reflect.Type type) |
static boolean |
isInnerClass(java.lang.Class<?> clazz) |
static boolean |
isMethodPresent(java.lang.Class<?> clazz,
java.util.function.Predicate<java.lang.reflect.Method> predicate)
Determine if a
Method matching the supplied Predicate
is 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. |
private static boolean |
isMethodShadowedBy(java.lang.reflect.Method upper,
java.lang.reflect.Method lower) |
private static boolean |
isMethodShadowedByLocalMethods(java.lang.reflect.Method method,
java.util.List<java.lang.reflect.Method> localMethods) |
static boolean |
isPrivate(java.lang.Class<?> clazz) |
static boolean |
isPrivate(java.lang.reflect.Member member) |
static boolean |
isPublic(java.lang.Class<?> clazz) |
static boolean |
isPublic(java.lang.reflect.Member member) |
static boolean |
isStatic(java.lang.Class<?> clazz) |
static boolean |
isStatic(java.lang.reflect.Member member) |
private static java.util.Optional<java.lang.Class<?>> |
loadArrayType(java.lang.ClassLoader classLoader,
java.lang.String componentTypeName,
int dimensions) |
static java.util.Optional<java.lang.Class<?>> |
loadClass(java.lang.String name) |
static java.util.Optional<java.lang.Class<?>> |
loadClass(java.lang.String name,
java.lang.ClassLoader classLoader)
Load a class by its primitive name or fully qualified name,
using the supplied
ClassLoader . |
static java.util.Optional<java.lang.reflect.Method> |
loadMethod(java.lang.String fullyQualifiedMethodName)
Load a method by its fully qualified name.
|
private static java.lang.Class<?> |
loadRequiredParameterType(java.lang.Class<?> clazz,
java.lang.String methodName,
java.lang.String typeName) |
static <T extends java.lang.reflect.AccessibleObject> |
makeAccessible(T object) |
static <T> T |
newInstance(java.lang.Class<T> clazz,
java.lang.Object... args) |
static <T> T |
newInstance(java.lang.reflect.Constructor<T> constructor,
java.lang.Object... args)
Create a new instance of type
T by invoking the supplied constructor
with the supplied arguments. |
static <T> java.util.Optional<java.lang.Object> |
readFieldValue(java.lang.Class<T> clazz,
java.lang.String fieldName,
T instance)
Read the value of a potentially inaccessible field.
|
private static java.lang.Class<?>[] |
resolveParameterTypes(java.lang.Class<?> clazz,
java.lang.String methodName,
java.lang.String parameterTypeNames) |
static boolean |
returnsVoid(java.lang.reflect.Method method) |
private static java.util.List<java.lang.reflect.Method> |
toSortedMutableList(java.lang.reflect.Method[] methods) |
private static final java.util.regex.Pattern FULLY_QUALIFIED_METHOD_NAME_PATTERN
private static final java.util.regex.Pattern VM_INTERNAL_OBJECT_ARRAY_PATTERN
private static final java.util.regex.Pattern VM_INTERNAL_PRIMITIVE_ARRAY_PATTERN
The pattern intentionally captures the last bracket with the
capital letter so that the combination can be looked up via
classNameToTypeMap
. For example, the last matched group
will contain "[I"
instead of simply "I"
.
Class.getName()
private static final java.util.regex.Pattern SOURCE_CODE_SYNTAX_ARRAY_PATTERN
private static final java.lang.Class<?>[] EMPTY_CLASS_ARRAY
private static final ClasspathScanner classpathScanner
private static final java.util.Map<java.lang.String,java.lang.Class<?>> classNameToTypeMap
private static final java.util.Map<java.lang.Class<?>,java.lang.Class<?>> primitiveToWrapperMap
public static boolean isPublic(java.lang.Class<?> clazz)
public static boolean isPublic(java.lang.reflect.Member member)
public static boolean isPrivate(java.lang.Class<?> clazz)
public static boolean isPrivate(java.lang.reflect.Member member)
public static boolean isAbstract(java.lang.Class<?> clazz)
public static boolean isAbstract(java.lang.reflect.Member member)
public static boolean isStatic(java.lang.Class<?> clazz)
public static boolean isStatic(java.lang.reflect.Member member)
public static boolean isInnerClass(java.lang.Class<?> clazz)
public static boolean returnsVoid(java.lang.reflect.Method method)
public static boolean isArray(java.lang.Object obj)
obj
- the object to test; potentially null
true
if the object is an arraypublic static boolean isAssignableTo(java.lang.Object obj, java.lang.Class<?> type)
In contrast to Class.isInstance(Object)
, this method returns
true
if the supplied type represents a primitive type whose
wrapper matches the supplied object's type.
Returns true
if the supplied object is null
and the
supplied type does not represent a primitive type.
obj
- the object to test for assignment compatibility; potentially null
type
- the type to check against; never null
true
if the object is assignment compatibleClass.isInstance(Object)
,
Class.isAssignableFrom(Class)
public static java.lang.Class<?> getWrapperType(java.lang.Class<?> type)
type
- the primitive type for which to retrieve the wrapper typenull
if the
supplied type is null
or not a primitive typepublic static <T> T newInstance(java.lang.Class<T> clazz, java.lang.Object... args)
public static <T> T newInstance(java.lang.reflect.Constructor<T> constructor, java.lang.Object... args)
T
by 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.
constructor
- the constructor to invoke; never null
args
- the arguments to pass to the constructornull
newInstance(Class, Object...)
,
ExceptionUtils.throwAsUncheckedException(Throwable)
public static <T> java.util.Optional<java.lang.Object> readFieldValue(java.lang.Class<T> clazz, java.lang.String fieldName, T instance)
If the field does not exist, an exception occurs while reading it, or
the value of the field is null
, an empty Optional
is
returned.
clazz
- the class where the field is declared; never null
fieldName
- the name of the field; never null
or emptyinstance
- the instance from where the value is to be read; may
be null
for a static fieldpublic static java.lang.Object invokeMethod(java.lang.reflect.Method method, java.lang.Object target, java.lang.Object... args)
public static java.util.Optional<java.lang.Class<?>> loadClass(java.lang.String name)
ReflectionSupport.loadClass(String)
public static java.util.Optional<java.lang.Class<?>> loadClass(java.lang.String name, java.lang.ClassLoader classLoader)
ClassLoader
.
See ReflectionSupport.loadClass(String)
for details on support for class names for arrays.
name
- the name of the class to load; never null
or blankclassLoader
- the ClassLoader
to use; never null
loadClass(String)
private static java.util.Optional<java.lang.Class<?>> loadArrayType(java.lang.ClassLoader classLoader, java.lang.String componentTypeName, int dimensions) throws java.lang.ClassNotFoundException
java.lang.ClassNotFoundException
public static java.util.Optional<java.lang.reflect.Method> loadMethod(java.lang.String fullyQualifiedMethodName)
The following formats are supported.
[fully qualified class name]#[methodName]
[fully qualified class name]#[methodName](parameter type list)
The parameter type list is a comma-separated list of primitive names or fully qualified class names for the types of parameters accepted by the method.
See loadClass(String, ClassLoader)
for details on the supported
syntax for array parameter types.
Method | Fully Qualified Method Name |
---|---|
java.lang.String.chars() | java.lang.String#chars |
java.lang.String.chars() | java.lang.String#chars() |
java.lang.String.equalsIgnoreCase(String) | java.lang.String#equalsIgnoreCase(java.lang.String) |
java.lang.String.substring(int, int) | java.lang.String#substring(int, int) |
example.Calc.avg(int[]) | example.Calc#avg([I) |
example.Calc.avg(int[]) | example.Calc#avg(int[]) |
example.Matrix.multiply(double[][]) | example.Matrix#multiply([[D) |
example.Matrix.multiply(double[][]) | example.Matrix#multiply(double[][]) |
example.Service.process(String[]) | example.Service#process([Ljava.lang.String;) |
example.Service.process(String[]) | example.Service#process(java.lang.String[]) |
example.Service.process(String[][]) | example.Service#process([[Ljava.lang.String;) |
example.Service.process(String[][]) | example.Service#process(java.lang.String[][]) |
fullyQualifiedMethodName
- the fully qualified name of the method to load;
never null
or blankOptional
containing the method; never null
but
potentially emptygetFullyQualifiedMethodName(Class, String, Class...)
public static java.lang.String getFullyQualifiedMethodName(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.Class<?>... parameterTypes)
See loadMethod(String)
for details on the format.
clazz
- the class that declares the method; never null
methodName
- the name of the method; never null
or blankparameterTypes
- the parameter types of the method; may be null
or emptynull
loadMethod(String)
public static java.util.Optional<java.lang.Object> getOutermostInstance(java.lang.Object inner, java.lang.Class<?> requiredType)
If the supplied inner object is of the required type, it will simply be returned.
inner
- the inner object from which to begin the search; never null
requiredType
- the required type of the outermost instance; never null
Optional
containing the outermost instance; never null
but potentially emptyprivate static java.util.Optional<java.lang.Object> getOuterInstance(java.lang.Object inner)
public static java.util.Set<java.nio.file.Path> getAllClasspathRootDirectories()
public static java.util.List<java.lang.Class<?>> findAllClassesInClasspathRoot(java.net.URI root, java.util.function.Predicate<java.lang.Class<?>> classTester, java.util.function.Predicate<java.lang.String> classNameFilter)
public static java.util.List<java.lang.Class<?>> findAllClassesInPackage(java.lang.String basePackageName, java.util.function.Predicate<java.lang.Class<?>> classTester, java.util.function.Predicate<java.lang.String> classNameFilter)
public static java.util.List<java.lang.Class<?>> findNestedClasses(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.Class<?>> predicate)
private static void findNestedClasses(java.lang.Class<?> clazz, java.util.Set<java.lang.Class<?>> candidates)
public static <T> java.lang.reflect.Constructor<T> getDeclaredConstructor(java.lang.Class<T> clazz)
Constructor
for the supplied class.
Throws a PreconditionViolationException
if the supplied
class declares more than one constructor.
clazz
- the class to get the constructor fornull
Class.getDeclaredConstructors()
public static boolean isMethodPresent(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.Method> predicate)
Method
matching the supplied Predicate
is 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.clazz
- the class or interface in which to find the method; never
null
predicate
- the predicate to use to test for a match; never
null
true
if such a method is presentfindMethod(Class, String, String)
,
findMethod(Class, String, Class...)
static java.util.Optional<java.lang.reflect.Method> getMethod(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.Class<?>... parameterTypes)
Method
in the specified class with the specified name
and parameter types.
This method delegates to Class.getMethod(String, Class...)
but
swallows any exception thrown.
clazz
- the class in which to search for the method; never null
methodName
- the name of the method to get; never null
or blankparameterTypes
- the parameter types of the method; may be null
or emptyOptional
containing the method; never null
but
empty if the invocation of Class#getMethod()
throws a
NoSuchMethodException
public static java.util.Optional<java.lang.reflect.Method> findMethod(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.String parameterTypeNames)
private static java.lang.Class<?>[] resolveParameterTypes(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.String parameterTypeNames)
private static java.lang.Class<?> loadRequiredParameterType(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.String typeName)
public static java.util.Optional<java.lang.reflect.Method> findMethod(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.Class<?>... parameterTypes)
private static java.util.Optional<java.lang.reflect.Method> findMethod(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.Method> predicate)
public static java.util.List<java.lang.reflect.Method> findMethods(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.Method> predicate)
predicate
, using top-down search semantics
within the type hierarchy.
The results will not contain instance methods that are overridden
or static
methods that are hidden.
clazz
- the class or interface in which to find the methods; never null
predicate
- the method filter; never null
null
ReflectionUtils.HierarchyTraversalMode.TOP_DOWN
,
findMethods(Class, Predicate, HierarchyTraversalMode)
public static java.util.List<java.lang.reflect.Method> findMethods(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.Method> predicate, ReflectionUtils.HierarchyTraversalMode traversalMode)
private static java.util.List<java.lang.reflect.Method> findAllMethodsInHierarchy(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)
private static java.util.List<java.lang.reflect.Method> getMethods(java.lang.Class<?> clazz)
Class.getMethods()
that sorts the methods
and converts them to a mutable list.private static java.util.List<java.lang.reflect.Method> getDeclaredMethods(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)
Class.getDeclaredMethods()
that sorts the
methods and converts them to a mutable list.
In addition, the list returned by this method includes interface default methods which are either prepended or appended to the list of declared methods depending on the supplied traversal mode.
private static java.util.List<java.lang.reflect.Method> getDefaultMethods(java.lang.Class<?> clazz)
private static java.util.List<java.lang.reflect.Method> toSortedMutableList(java.lang.reflect.Method[] methods)
private static int defaultMethodSorter(java.lang.reflect.Method method1, java.lang.reflect.Method method2)
org.junit.internal.MethodSorter
implementation.private static java.util.List<java.lang.reflect.Method> getInterfaceMethods(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)
private static java.util.List<java.lang.reflect.Method> getSuperclassMethods(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)
private static boolean isMethodShadowedByLocalMethods(java.lang.reflect.Method method, java.util.List<java.lang.reflect.Method> localMethods)
private static boolean isMethodShadowedBy(java.lang.reflect.Method upper, java.lang.reflect.Method lower)
private static boolean hasCompatibleSignature(java.lang.reflect.Method candidate, java.lang.String methodName, java.lang.Class<?>[] parameterTypes)
static boolean isGeneric(java.lang.reflect.Method method)
private static boolean isGeneric(java.lang.reflect.Type type)
public static <T extends java.lang.reflect.AccessibleObject> T makeAccessible(T object)
public static java.util.Set<java.lang.Class<?>> getAllAssignmentCompatibleClasses(java.lang.Class<?> clazz)
Class
, including itself.clazz
- the Class
to look upClass.isAssignableFrom(java.lang.Class<?>)
private static void getAllAssignmentCompatibleClasses(java.lang.Class<?> clazz, java.util.Set<java.lang.Class<?>> result)
private static java.lang.Throwable getUnderlyingCause(java.lang.Throwable t)
Throwable
.
If the supplied Throwable
is an instance of
InvocationTargetException
, this method will be invoked
recursively with the underlying
target
exception; otherwise, this method simply returns the supplied
Throwable
.