Class ReflectionUtils
- java.lang.Object
-
- org.junit.platform.commons.util.ReflectionUtils
-
@API(status=INTERNAL, since="1.0") public final class ReflectionUtils extends java.lang.ObjectCollection 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.
-
Field Summary
Fields Modifier and Type Field Description private static java.util.Map<java.lang.String,java.lang.Class<?>>classNameToTypeMapInternal cache of common class names mapped to their types.private static ClasspathScannerclasspathScannerprivate static java.lang.Class<?>[]EMPTY_CLASS_ARRAYprivate static Loggerloggerprivate static java.util.Set<java.lang.String>noCyclesDetectedCacheSet of fully qualified class names for which no cycles have been detected in inner class hierarchies.private static java.util.Map<java.lang.Class<?>,java.lang.Class<?>>primitiveToWrapperMapInternal cache of primitive types mapped to their wrapper types.private static java.util.regex.PatternSOURCE_CODE_SYNTAX_ARRAY_PATTERNprivate static java.util.regex.PatternVM_INTERNAL_OBJECT_ARRAY_PATTERNprivate static java.util.regex.PatternVM_INTERNAL_PRIMITIVE_ARRAY_PATTERNPattern: "[x", "[[[[x", etc., where x is Z, B, C, D, F, I, J, S, etc.
-
Constructor Summary
Constructors Modifier Constructor Description privateReflectionUtils()
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description private static intdefaultFieldSorter(java.lang.reflect.Field field1, java.lang.reflect.Field field2)Field comparator inspired by JUnit 4'sorg.junit.internal.MethodSorterimplementation.private static intdefaultMethodSorter(java.lang.reflect.Method method1, java.lang.reflect.Method method2)Method comparator based upon JUnit 4'sorg.junit.internal.MethodSorterimplementation.private static voiddetectInnerClassCycle(java.lang.Class<?> clazz)Detect a cycle in the inner class hierarchy in which the supplied class resides — from the supplied class up to the outermost enclosing class — and throw aJUnitExceptionif a cycle is detected.static java.util.List<java.lang.Class<?>>findAllClassesInClasspathRoot(java.net.URI root, java.util.function.Predicate<java.lang.Class<?>> classFilter, java.util.function.Predicate<java.lang.String> classNameFilter)static java.util.List<java.lang.Class<?>>findAllClassesInClasspathRoot(java.net.URI root, ClassFilter classFilter)static java.util.List<java.lang.Class<?>>findAllClassesInModule(java.lang.String moduleName, java.util.function.Predicate<java.lang.Class<?>> classFilter, java.util.function.Predicate<java.lang.String> classNameFilter)static java.util.List<java.lang.Class<?>>findAllClassesInModule(java.lang.String moduleName, ClassFilter classFilter)static java.util.List<java.lang.Class<?>>findAllClassesInPackage(java.lang.String basePackageName, java.util.function.Predicate<java.lang.Class<?>> classFilter, java.util.function.Predicate<java.lang.String> classNameFilter)static java.util.List<java.lang.Class<?>>findAllClassesInPackage(java.lang.String basePackageName, ClassFilter classFilter)private static java.util.List<java.lang.reflect.Field>findAllFieldsInHierarchy(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)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.static java.util.List<java.lang.reflect.Constructor<?>>findConstructors(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.Constructor<?>> predicate)Find all constructors in the supplied class that match the supplied predicate.static java.util.List<java.lang.reflect.Field>findFields(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.Field> predicate, ReflectionUtils.HierarchyTraversalMode traversalMode)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)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.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 specifiedpredicate, 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 voidfindNestedClasses(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.Class<?>> predicate, 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 specifiedClass, including itself.private static voidgetAllAssignmentCompatibleClasses(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, non-syntheticConstructorfor the supplied class.private static java.util.List<java.lang.reflect.Field>getDeclaredFields(java.lang.Class<?> clazz)Custom alternative toClass.getDeclaredFields()that sorts the fields and converts them to a mutable list.private static java.util.List<java.lang.reflect.Method>getDeclaredMethods(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)Custom alternative toClass.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.private static java.util.List<java.lang.reflect.Field>getFields(java.lang.Class<?> clazz)Custom alternative toClass.getFields()that sorts the fields and converts them to a mutable list.static java.lang.StringgetFullyQualifiedMethodName(java.lang.Class<?> clazz, java.lang.reflect.Method method)Build the fully qualified method name for the method described by the supplied class and method.static java.lang.StringgetFullyQualifiedMethodName(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.Field>getInterfaceFields(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)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)Deprecated.Please usetryToGetMethod(Class, String, Class[])instead.private static java.util.List<java.lang.reflect.Method>getMethods(java.lang.Class<?> clazz)Custom alternative toClass.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)Deprecated.Please discontinue use of this method since it relies on internal implementation details of the JDK that may not work in the future.static java.lang.reflect.MethodgetRequiredMethod(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.Class<?>... parameterTypes)Find the firstMethodof the supplied class or interface that meets the specified criteria, 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 java.util.List<java.lang.reflect.Field>getSuperclassFields(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 java.lang.ThrowablegetUnderlyingCause(java.lang.Throwable t)Get the underlying cause of the suppliedThrowable.static java.lang.Class<?>getWrapperType(java.lang.Class<?> type)Get the wrapper type for the supplied primitive type.private static booleanhasCompatibleSignature(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.ObjectinvokeMethod(java.lang.reflect.Method method, java.lang.Object target, java.lang.Object... args)static booleanisAbstract(java.lang.Class<?> clazz)static booleanisAbstract(java.lang.reflect.Member member)static booleanisArray(java.lang.Object obj)Determine if the supplied object is an array.static booleanisAssignableTo(java.lang.Object obj, java.lang.Class<?> targetType)Determine if the supplied object can be assigned to the supplied target type for the purpose of reflective method invocations.private static booleanisFieldShadowedByLocalFields(java.lang.reflect.Field field, java.util.List<java.lang.reflect.Field> localFields)static booleanisFinal(java.lang.Class<?> clazz)static booleanisFinal(java.lang.reflect.Member member)(package private) static booleanisGeneric(java.lang.reflect.Method method)private static booleanisGeneric(java.lang.reflect.Type type)static booleanisInnerClass(java.lang.Class<?> clazz)Determine if the supplied class is an inner class (i.e., a non-static member class).static booleanisMethodPresent(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.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.private static booleanisMethodShadowedBy(java.lang.reflect.Method upper, java.lang.reflect.Method lower)private static booleanisMethodShadowedByLocalMethods(java.lang.reflect.Method method, java.util.List<java.lang.reflect.Method> localMethods)static booleanisMultidimensionalArray(java.lang.Object obj)Determine if the supplied object is a multidimensional array.static booleanisNotFinal(java.lang.Class<?> clazz)static booleanisNotFinal(java.lang.reflect.Member member)static booleanisNotPrivate(java.lang.Class<?> clazz)static booleanisNotPrivate(java.lang.reflect.Member member)static booleanisNotStatic(java.lang.Class<?> clazz)static booleanisNotStatic(java.lang.reflect.Member member)static booleanisPrivate(java.lang.Class<?> clazz)static booleanisPrivate(java.lang.reflect.Member member)static booleanisPublic(java.lang.Class<?> clazz)static booleanisPublic(java.lang.reflect.Member member)private static booleanisSearchable(java.lang.Class<?> clazz)Determine if the supplied class is searchable: is non-null and is not equal to the class reference forjava.lang.Object.static booleanisStatic(java.lang.Class<?> clazz)static booleanisStatic(java.lang.reflect.Member member)(package private) static booleanisWideningConversion(java.lang.Class<?> sourceType, java.lang.Class<?> targetType)Determine if Java supports a widening primitive conversion from the supplied source type to the supplied primitive target type.private static 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)Deprecated.Please usetryToLoadClass(String)instead.static java.util.Optional<java.lang.Class<?>>loadClass(java.lang.String name, java.lang.ClassLoader classLoader)Deprecated.Please usetryToLoadClass(String, ClassLoader)instead.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>
TmakeAccessible(T object)static <T> TnewInstance(java.lang.Class<T> clazz, java.lang.Object... args)static <T> TnewInstance(java.lang.reflect.Constructor<T> constructor, java.lang.Object... args)Create a new instance of typeTby invoking the supplied constructor with the supplied arguments.static java.lang.String[]parseFullyQualifiedMethodName(java.lang.String fullyQualifiedMethodName)Parse the supplied fully qualified method name into a 3-elementString[]with the following content.static <T> java.util.Optional<java.lang.Object>readFieldValue(java.lang.Class<T> clazz, java.lang.String fieldName, T instance)Deprecated.Please usetryToReadFieldValue(Class, String, Object)instead.static java.util.Optional<java.lang.Object>readFieldValue(java.lang.reflect.Field field)Deprecated.Please usetryToReadFieldValue(Field)instead.static java.util.Optional<java.lang.Object>readFieldValue(java.lang.reflect.Field field, java.lang.Object instance)Deprecated.Please usetryToReadFieldValue(Field, Object)instead.static java.util.List<java.lang.Object>readFieldValues(java.util.List<java.lang.reflect.Field> fields, java.lang.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 java.util.List<java.lang.Object>readFieldValues(java.util.List<java.lang.reflect.Field> fields, java.lang.Object instance, java.util.function.Predicate<java.lang.reflect.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.private static java.lang.Class<?>[]resolveParameterTypes(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.String parameterTypeNames)static booleanreturnsVoid(java.lang.reflect.Method method)private static java.util.List<java.lang.reflect.Field>toSortedMutableList(java.lang.reflect.Field[] fields)private static java.util.List<java.lang.reflect.Method>toSortedMutableList(java.lang.reflect.Method[] methods)static Try<java.lang.reflect.Method>tryToGetMethod(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.Class<?>... parameterTypes)Try to get theMethodin the specified class with the specified name and parameter types.static Try<java.lang.Class<?>>tryToLoadClass(java.lang.String name)static Try<java.lang.Class<?>>tryToLoadClass(java.lang.String name, java.lang.ClassLoader classLoader)Try to load a class by its primitive name or fully qualified name, using the suppliedClassLoader.static <T> Try<java.lang.Object>tryToReadFieldValue(java.lang.Class<T> clazz, java.lang.String fieldName, T instance)Try to read the value of a potentially inaccessible or nonexistent field.static Try<java.lang.Object>tryToReadFieldValue(java.lang.reflect.Field field)Try to read the value of a potentially inaccessible static field.static Try<java.lang.Object>tryToReadFieldValue(java.lang.reflect.Field field, java.lang.Object instance)
-
-
-
Field Detail
-
logger
private static final Logger logger
-
VM_INTERNAL_OBJECT_ARRAY_PATTERN
private static final java.util.regex.Pattern VM_INTERNAL_OBJECT_ARRAY_PATTERN
-
VM_INTERNAL_PRIMITIVE_ARRAY_PATTERN
private static final 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.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".- See Also:
Class.getName()
-
SOURCE_CODE_SYNTAX_ARRAY_PATTERN
private static final java.util.regex.Pattern SOURCE_CODE_SYNTAX_ARRAY_PATTERN
-
EMPTY_CLASS_ARRAY
private static final java.lang.Class<?>[] EMPTY_CLASS_ARRAY
-
classpathScanner
private static final ClasspathScanner classpathScanner
-
noCyclesDetectedCache
private static final java.util.Set<java.lang.String> noCyclesDetectedCache
Set of fully qualified class names for which no cycles have been detected in inner class hierarchies.This serves as a cache to avoid repeated cycle detection for classes that have already been checked.
- Since:
- 1.6
- See Also:
detectInnerClassCycle(Class)
-
classNameToTypeMap
private static final java.util.Map<java.lang.String,java.lang.Class<?>> classNameToTypeMap
Internal cache of common class names mapped to their types.
-
primitiveToWrapperMap
private static final java.util.Map<java.lang.Class<?>,java.lang.Class<?>> primitiveToWrapperMap
Internal cache of primitive types mapped to their wrapper types.
-
-
Method Detail
-
isPublic
public static boolean isPublic(java.lang.Class<?> clazz)
-
isPublic
public static boolean isPublic(java.lang.reflect.Member member)
-
isPrivate
public static boolean isPrivate(java.lang.Class<?> clazz)
-
isPrivate
public static boolean isPrivate(java.lang.reflect.Member member)
-
isNotPrivate
@API(status=INTERNAL, since="1.4") public static boolean isNotPrivate(java.lang.Class<?> clazz)
-
isNotPrivate
@API(status=INTERNAL, since="1.1") public static boolean isNotPrivate(java.lang.reflect.Member member)
-
isAbstract
public static boolean isAbstract(java.lang.Class<?> clazz)
-
isAbstract
public static boolean isAbstract(java.lang.reflect.Member member)
-
isStatic
public static boolean isStatic(java.lang.Class<?> clazz)
-
isNotStatic
@API(status=INTERNAL, since="1.4") public static boolean isNotStatic(java.lang.Class<?> clazz)
-
isStatic
public static boolean isStatic(java.lang.reflect.Member member)
-
isNotStatic
@API(status=INTERNAL, since="1.1") public static boolean isNotStatic(java.lang.reflect.Member member)
-
isFinal
@API(status=INTERNAL, since="1.5") public static boolean isFinal(java.lang.Class<?> clazz)- Since:
- 1.5
-
isNotFinal
@API(status=INTERNAL, since="1.5") public static boolean isNotFinal(java.lang.Class<?> clazz)- Since:
- 1.5
-
isFinal
@API(status=INTERNAL, since="1.5") public static boolean isFinal(java.lang.reflect.Member member)- Since:
- 1.5
-
isNotFinal
@API(status=INTERNAL, since="1.5") public static boolean isNotFinal(java.lang.reflect.Member member)- Since:
- 1.5
-
isInnerClass
public static boolean isInnerClass(java.lang.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(java.lang.reflect.Method method)
-
isArray
public static boolean isArray(java.lang.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(java.lang.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(java.lang.Object obj, java.lang.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)
-
isWideningConversion
static boolean isWideningConversion(java.lang.Class<?> sourceType, java.lang.Class<?> targetType)Determine if Java supports a widening primitive conversion from the supplied source type to the supplied primitive target type.
-
getWrapperType
public static java.lang.Class<?> getWrapperType(java.lang.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(java.lang.Class<T> clazz, java.lang.Object... args)
-
newInstance
public static <T> T newInstance(java.lang.reflect.Constructor<T> constructor, java.lang.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> java.util.Optional<java.lang.Object> readFieldValue(java.lang.Class<T> clazz, java.lang.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<java.lang.Object> tryToReadFieldValue(java.lang.Class<T> clazz, java.lang.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 java.util.Optional<java.lang.Object> readFieldValue(java.lang.reflect.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<java.lang.Object> tryToReadFieldValue(java.lang.reflect.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 java.util.Optional<java.lang.Object> readFieldValue(java.lang.reflect.Field field, java.lang.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<java.lang.Object> tryToReadFieldValue(java.lang.reflect.Field field, java.lang.Object instance)
-
readFieldValues
public static java.util.List<java.lang.Object> readFieldValues(java.util.List<java.lang.reflect.Field> fields, java.lang.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 java.util.List<java.lang.Object> readFieldValues(java.util.List<java.lang.reflect.Field> fields, java.lang.Object instance, java.util.function.Predicate<java.lang.reflect.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
-
invokeMethod
public static java.lang.Object invokeMethod(java.lang.reflect.Method method, java.lang.Object target, java.lang.Object... args)
-
loadClass
@API(status=DEPRECATED, since="1.4") @Deprecated public static java.util.Optional<java.lang.Class<?>> loadClass(java.lang.String name)Deprecated.Please usetryToLoadClass(String)instead.- See Also:
ReflectionSupport.loadClass(String)
-
tryToLoadClass
@API(status=INTERNAL, since="1.4") public static Try<java.lang.Class<?>> tryToLoadClass(java.lang.String name)- Since:
- 1.4
- See Also:
ReflectionSupport.tryToLoadClass(String)
-
loadClass
@API(status=DEPRECATED, since="1.4") @Deprecated public static java.util.Optional<java.lang.Class<?>> loadClass(java.lang.String name, java.lang.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<java.lang.Class<?>> tryToLoadClass(java.lang.String name, java.lang.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)
-
loadArrayType
private static java.lang.Class<?> loadArrayType(java.lang.ClassLoader classLoader, java.lang.String componentTypeName, int dimensions) throws java.lang.ClassNotFoundException- Throws:
java.lang.ClassNotFoundException
-
getFullyQualifiedMethodName
public static java.lang.String getFullyQualifiedMethodName(java.lang.Class<?> clazz, java.lang.reflect.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 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.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 java.lang.String[] parseFullyQualifiedMethodName(java.lang.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 java.util.Optional<java.lang.Object> getOutermostInstance(java.lang.Object inner, java.lang.Class<?> requiredType)Deprecated.Please discontinue use of this method since it relies on internal implementation details of the JDK that may not work in the future.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
-
getOuterInstance
private static java.util.Optional<java.lang.Object> getOuterInstance(java.lang.Object inner)
-
getAllClasspathRootDirectories
public static java.util.Set<java.nio.file.Path> getAllClasspathRootDirectories()
-
findAllClassesInClasspathRoot
public static java.util.List<java.lang.Class<?>> findAllClassesInClasspathRoot(java.net.URI root, java.util.function.Predicate<java.lang.Class<?>> classFilter, java.util.function.Predicate<java.lang.String> classNameFilter)
-
findAllClassesInClasspathRoot
public static java.util.List<java.lang.Class<?>> findAllClassesInClasspathRoot(java.net.URI root, ClassFilter classFilter)- Since:
- 1.1
-
findAllClassesInPackage
public static java.util.List<java.lang.Class<?>> findAllClassesInPackage(java.lang.String basePackageName, java.util.function.Predicate<java.lang.Class<?>> classFilter, java.util.function.Predicate<java.lang.String> classNameFilter)
-
findAllClassesInPackage
public static java.util.List<java.lang.Class<?>> findAllClassesInPackage(java.lang.String basePackageName, ClassFilter classFilter)- Since:
- 1.1
-
findAllClassesInModule
public static java.util.List<java.lang.Class<?>> findAllClassesInModule(java.lang.String moduleName, java.util.function.Predicate<java.lang.Class<?>> classFilter, java.util.function.Predicate<java.lang.String> classNameFilter)- Since:
- 1.1.1
- See Also:
ReflectionSupport.findAllClassesInModule(String, Predicate, Predicate)
-
findAllClassesInModule
public static java.util.List<java.lang.Class<?>> findAllClassesInModule(java.lang.String moduleName, ClassFilter classFilter)- Since:
- 1.1.1
-
findNestedClasses
public static java.util.List<java.lang.Class<?>> findNestedClasses(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.Class<?>> predicate)
-
findNestedClasses
private static void findNestedClasses(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.Class<?>> predicate, java.util.Set<java.lang.Class<?>> candidates)
-
detectInnerClassCycle
private static void detectInnerClassCycle(java.lang.Class<?> clazz)
Detect a cycle in the inner class hierarchy in which the supplied class resides — from the supplied class up to the outermost enclosing class — and throw aJUnitExceptionif a cycle is detected.This method does not detect cycles within inner class hierarchies below the supplied class.
If the supplied class is not an inner class and does not have a searchable superclass, this method is effectively a no-op.
- Since:
- 1.6
- See Also:
isInnerClass(Class),isSearchable(Class)
-
getDeclaredConstructor
public static <T> java.lang.reflect.Constructor<T> getDeclaredConstructor(java.lang.Class<T> clazz)
Get the sole declared, non-syntheticConstructorfor the supplied class.Throws a
PreconditionViolationExceptionif the supplied class declares more than one non-synthetic constructor.- Parameters:
clazz- the class to get the constructor for- Returns:
- the sole declared constructor; never
null - See Also:
Class.getDeclaredConstructors(),Class.isSynthetic()
-
findConstructors
public static java.util.List<java.lang.reflect.Constructor<?>> findConstructors(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.Constructor<?>> predicate)Find all constructors in the supplied class that match the supplied predicate.Note that this method may return synthetic constructors. If you wish to ignore synthetic constructors, you may filter them out with the supplied
predicateor filter them out of the list returned by this method.- 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 - See Also:
Class.getDeclaredConstructors(),Class.isSynthetic()
-
findFields
public static java.util.List<java.lang.reflect.Field> findFields(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.Field> predicate, ReflectionUtils.HierarchyTraversalMode traversalMode)
-
findAllFieldsInHierarchy
private static java.util.List<java.lang.reflect.Field> findAllFieldsInHierarchy(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)
-
isMethodPresent
public static boolean isMethodPresent(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.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...)
-
getMethod
@API(status=DEPRECATED, since="1.4") @Deprecated static java.util.Optional<java.lang.reflect.Method> getMethod(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.Class<?>... parameterTypes)Deprecated.Please usetryToGetMethod(Class, String, Class[])instead.Get theMethodin the specified class with the specified name and parameter types.This method delegates to
Class.getMethod(String, Class...)but swallows 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:
- an
Optionalcontaining the method; nevernullbut empty if the invocation ofClass#getMethod()throws aNoSuchMethodException
-
tryToGetMethod
@API(status=INTERNAL, since="1.4") public static Try<java.lang.reflect.Method> tryToGetMethod(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.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 java.util.Optional<java.lang.reflect.Method> findMethod(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.String parameterTypeNames)
-
resolveParameterTypes
private static java.lang.Class<?>[] resolveParameterTypes(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.String parameterTypeNames)
-
loadRequiredParameterType
private static java.lang.Class<?> loadRequiredParameterType(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.String typeName)
-
findMethod
public static java.util.Optional<java.lang.reflect.Method> findMethod(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.Class<?>... parameterTypes)
-
findMethod
private static java.util.Optional<java.lang.reflect.Method> findMethod(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.Method> predicate)
-
getRequiredMethod
@API(status=STABLE, since="1.7") public static java.lang.reflect.Method getRequiredMethod(java.lang.Class<?> clazz, java.lang.String methodName, java.lang.Class<?>... parameterTypes)Find the firstMethodof the supplied class or interface that meets the specified criteria, 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.Use this method as an alternative to
findMethod(Class, String, Class...)for use cases in which the method is required to be present.- Parameters:
clazz- the class or interface in which to find the method; nevernullmethodName- the name of the method to find; nevernullor emptyparameterTypes- the types of parameters accepted by the method, if any; nevernull- Returns:
- the
Methodfound; nevernull - Throws:
JUnitException- if no method is found- Since:
- 1.7
- See Also:
findMethod(Class, String, Class...)
-
findMethods
public 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 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 java.util.List<java.lang.reflect.Method> findMethods(java.lang.Class<?> clazz, java.util.function.Predicate<java.lang.reflect.Method> predicate, ReflectionUtils.HierarchyTraversalMode traversalMode)
-
findAllMethodsInHierarchy
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.
-
getFields
private static java.util.List<java.lang.reflect.Field> getFields(java.lang.Class<?> clazz)
Custom alternative toClass.getFields()that sorts the fields and converts them to a mutable list.
-
getDeclaredFields
private static java.util.List<java.lang.reflect.Field> getDeclaredFields(java.lang.Class<?> clazz)
Custom alternative toClass.getDeclaredFields()that sorts the fields and converts them to a mutable list.
-
getMethods
private static java.util.List<java.lang.reflect.Method> getMethods(java.lang.Class<?> clazz)
Custom alternative toClass.getMethods()that sorts the methods and converts them to a mutable list.
-
getDeclaredMethods
private static java.util.List<java.lang.reflect.Method> getDeclaredMethods(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)Custom alternative toClass.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.
-
getDefaultMethods
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.- See Also:
- Method Visibility in the Java Language Specification
-
toSortedMutableList
private static java.util.List<java.lang.reflect.Field> toSortedMutableList(java.lang.reflect.Field[] fields)
-
toSortedMutableList
private static java.util.List<java.lang.reflect.Method> toSortedMutableList(java.lang.reflect.Method[] methods)
-
defaultFieldSorter
private static int defaultFieldSorter(java.lang.reflect.Field field1, java.lang.reflect.Field field2)Field comparator inspired by JUnit 4'sorg.junit.internal.MethodSorterimplementation.
-
defaultMethodSorter
private static int defaultMethodSorter(java.lang.reflect.Method method1, java.lang.reflect.Method method2)Method comparator based upon JUnit 4'sorg.junit.internal.MethodSorterimplementation.
-
getInterfaceMethods
private static java.util.List<java.lang.reflect.Method> getInterfaceMethods(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)
-
getInterfaceFields
private static java.util.List<java.lang.reflect.Field> getInterfaceFields(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)
-
getSuperclassFields
private static java.util.List<java.lang.reflect.Field> getSuperclassFields(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)
-
isFieldShadowedByLocalFields
private static boolean isFieldShadowedByLocalFields(java.lang.reflect.Field field, java.util.List<java.lang.reflect.Field> localFields)
-
getSuperclassMethods
private static java.util.List<java.lang.reflect.Method> getSuperclassMethods(java.lang.Class<?> clazz, ReflectionUtils.HierarchyTraversalMode traversalMode)
-
isMethodShadowedByLocalMethods
private static boolean isMethodShadowedByLocalMethods(java.lang.reflect.Method method, java.util.List<java.lang.reflect.Method> localMethods)
-
isMethodShadowedBy
private static boolean isMethodShadowedBy(java.lang.reflect.Method upper, java.lang.reflect.Method lower)
-
hasCompatibleSignature
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.
-
isGeneric
static boolean isGeneric(java.lang.reflect.Method method)
-
isGeneric
private static boolean isGeneric(java.lang.reflect.Type type)
-
makeAccessible
public static <T extends java.lang.reflect.AccessibleObject> T makeAccessible(T object)
-
getAllAssignmentCompatibleClasses
public 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 specifiedClass, including itself.- Parameters:
clazz- theClassto look up- See Also:
Class.isAssignableFrom(java.lang.Class<?>)
-
getAllAssignmentCompatibleClasses
private static void getAllAssignmentCompatibleClasses(java.lang.Class<?> clazz, java.util.Set<java.lang.Class<?>> result)
-
isSearchable
private static boolean isSearchable(java.lang.Class<?> clazz)
Determine if the supplied class is searchable: is non-null and is not equal to the class reference forjava.lang.Object.This method is often used to determine if a superclass should be searched but may be applicable for other use cases as well.
- Since:
- 1.6
-
getUnderlyingCause
private static java.lang.Throwable getUnderlyingCause(java.lang.Throwable t)
Get the underlying cause of the suppliedThrowable.If the supplied
Throwableis an instance ofInvocationTargetException, this method will be invoked recursively with the underlying target exception; otherwise, this method simply returns the suppliedThrowable.
-
-