Class ReflectionUtils
- java.lang.Object
-
- org.bardframework.commons.utils.ReflectionUtils
-
public final class ReflectionUtils extends Object
Created by Vahid Zafari on 8/12/2016.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceReflectionUtils.DescribedFieldFilterAReflectionUtils.FieldFilterthat has a description.static interfaceReflectionUtils.FieldCallbackCallback interface invoked on each field in the hierarchy.static interfaceReflectionUtils.FieldFilterCallback optionally used to filter fields to be operated on by a field callback.static interfaceReflectionUtils.MethodCallbackAction to take on each method.static interfaceReflectionUtils.MethodFilterCallback optionally used to filter methods to be operated on by a method callback.
-
Field Summary
Fields Modifier and Type Field Description static ReflectionUtils.FieldFilterCOPYABLE_FIELDSPre-built FieldFilter that matches all non-static, non-final fields.static ReflectionUtils.MethodFilterUSER_DECLARED_METHODSPre-built MethodFilter that matches all non-bridge non-synthetic methods which are not declared onjava.lang.Object.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static <T> Constructor<T>accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)Obtain an accessible constructor for the given class and parameters.static booleandeclaresException(Method method, Class<?> exceptionType)Determine whether the given method explicitly declares the given exception or one of its superclasses, which means that an exception of that type can be propagated as-is within a reflective invocation.static voiddoWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc)Invoke the given callback on all fields in the target class, going up the class hierarchy to get all declared fields.static voiddoWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc, ReflectionUtils.FieldFilter ff)Invoke the given callback on all fields in the target class, going up the class hierarchy to get all declared fields.static voiddoWithLocalFields(Class<?> clazz, ReflectionUtils.FieldCallback fc)Invoke the given callback on all locally declared fields in the given class.static voiddoWithLocalMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc)Perform the given callback operation on all matching methods of the given class, as locally declared or equivalent thereof (such as default methods on Java 8 based interfaces that the given class implements).static voiddoWithMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc)Perform the given callback operation on all matching methods of the given class and superclasses.static voiddoWithMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc, ReflectionUtils.MethodFilter mf)Perform the given callback operation on all matching methods of the given class and superclasses (or given interface and super-interfaces).static Set<String>fetchPropertyFields(Set<String> allFields, String fieldName)static FieldfindField(Class<?> clazz, String name)static FieldfindField(Class<?> clazz, String name, Class<?> type)static FieldfindField(Class<?> type, ReflectionUtils.DescribedFieldFilter filter)Finds the field matching the givenReflectionUtils.DescribedFieldFilter.static FieldfindField(Class<?> type, ReflectionUtils.DescribedFieldFilter filter, boolean enforceUniqueness)Finds the field matching the givenReflectionUtils.DescribedFieldFilter.static FieldfindField(Class<?> type, ReflectionUtils.FieldFilter filter)Finds the first field on the given class matching the givenReflectionUtils.FieldFilter.static MethodfindMethod(Class<?> clazz, String name)Attempt to find aMethodon the supplied class with the supplied name and no parameters.static MethodfindMethod(Class<?> clazz, String name, Class<?>... paramTypes)Attempt to find aMethodon the supplied class with the supplied name and parameter types.static FieldfindRequiredField(Class<?> type, String name)Finds the field of the given name on the given type.static MethodfindRequiredMethod(Class<?> type, String name, Class<?>... parameterTypes)Returns the method with the given name of the given class and parameter types.static Method[]getAllDeclaredMethods(Class<?> leafClass)Get all declared methods on the leaf class and all superclasses.static Class<?>getContainerCLassByField(Class<?> clazz, String fieldPath)static Class<?>getContainerClassByGetter(Class<?> clazz, String fieldPath)static MethodgetCurrentMethod(StackTraceElement stackTraceElement)static FieldgetDeclaredField(Class<?> clazz, String name)static Method[]getDeclaredMethods(Class<?> clazz)Variant ofClass.getDeclaredMethods()that uses a local cache in order to avoid the JVM's SecurityManager check and new Method instances.static FieldgetField(Class<?> clazz, String fieldPath)static ObjectgetField(Field field, Object target)Get the field represented by the suppliedfield objecton the specifiedtarget object.static <T extends Annotation>
Map<Field,T>getFieldAnnotationMap(Class<?> clazz, Class<T> annotationClazz, boolean includeSuperClasses)static <T extends Annotation>
List<Field>getFields(Class<?> clazz, Class<T> annotationClazz, boolean includeSuperClasses)static <T> Class<T>getGenericArgType(Class<?> clazz, int genericArgIndex)static MethodgetGetter(Class<?> aClass, String property)static MethodgetGetterMethod(Class<?> clazz, String fieldPath)static StringgetGetterName(String property, Class<?> type)static ObjectgetPrimitiveDefault(Class<?> type)Get default value for a primitive type.static ObjectgetPropertyValue(Object root, String propertyPath)static MethodgetSetter(Class<?> aClass, String property, Class<?>... parameterType)static StringgetSetterName(String property)static <T> Set<Class<? extends T>>getSubTypeOf(String packagePrefix, Class<T> clazz)static List<Class<?>>getSupersOf(Class<?> clazz, boolean includeInterface, boolean includeAbstractClasses, boolean includeObjectClass)static Method[]getUniqueDeclaredMethods(Class<?> leafClass)Get the unique set of declared methods on the leaf class and all superclasses.static Method[]getUniqueDeclaredMethods(Class<?> leafClass, ReflectionUtils.MethodFilter mf)Get the unique set of declared methods on the leaf class and all superclasses.static voidhandleInvocationTargetException(InvocationTargetException ex)Handle the given invocation target exception.static voidhandleReflectionException(Exception ex)Handle the given reflection exception.static ObjectinvokeMethod(Method method, Object target)Invoke the specifiedMethodagainst the supplied target object with no arguments.static ObjectinvokeMethod(Method method, Object target, Object... args)Invoke the specifiedMethodagainst the supplied target object with the supplied arguments.static booleanisCglibRenamedMethod(Method renamedMethod)Determine whether the given method is a CGLIB 'renamed' method, following the pattern "CGLIB$methodName$0".static booleanisContainField(Set<String> fields, String fieldName)static booleanisEqualsMethod(Method method)Determine whether the given method is an "equals" method.static booleanisHashCodeMethod(Method method)Determine whether the given method is a "hashCode" method.static booleanisObjectMethod(Method method)Determine whether the given method is originally declared byObject.static booleanisPublicStaticFinal(Field field)Determine whether the given field is a "public static final" constant.static booleanisToStringMethod(Method method)Determine whether the given method is a "toString" method.static StringlowerCaseFirstLetter(String name)static voidmakeAccessible(Constructor<?> ctor)Make the given constructor accessible, explicitly setting it accessible if necessary.static voidmakeAccessible(Field field)Make the given field accessible, explicitly setting it accessible if necessary.static voidmakeAccessible(Method method)Make the given method accessible, explicitly setting it accessible if necessary.static StringmethodToFieldName(Method method)static <T> TnewInstance(Class<T> clazz)static voidrethrowException(Throwable ex)Rethrow the givenexception, which is presumably the target exception of anInvocationTargetException.static voidrethrowRuntimeException(Throwable ex)Rethrow the givenexception, which is presumably the target exception of anInvocationTargetException.static Stream<Class<?>>returnTypeAndParameters(Method method)static voidsetField(Field field, Object target, Object value)Set the field represented by the supplied field object on the specified target object to the specifiedvalue.static ObjectsetValue(Object root, String path, Object value)static voidshallowCopyFieldState(Object src, Object dest)Given the source object and the destination, which must be the same class or a subclass, copy all fields, including inherited fields.
-
-
-
Field Detail
-
USER_DECLARED_METHODS
public static final ReflectionUtils.MethodFilter USER_DECLARED_METHODS
Pre-built MethodFilter that matches all non-bridge non-synthetic methods which are not declared onjava.lang.Object.
-
COPYABLE_FIELDS
public static final ReflectionUtils.FieldFilter COPYABLE_FIELDS
Pre-built FieldFilter that matches all non-static, non-final fields.
-
-
Method Detail
-
newInstance
public static <T> T newInstance(Class<T> clazz)
-
getGenericArgType
public static <T> Class<T> getGenericArgType(Class<?> clazz, int genericArgIndex)
-
findField
public static Field findField(Class<?> type, ReflectionUtils.FieldFilter filter)
Finds the first field on the given class matching the givenReflectionUtils.FieldFilter.- Parameters:
type- must not be null.filter- must not be null.- Returns:
- the field matching the filter or null in case no field could be found.
-
findField
public static Field findField(Class<?> type, ReflectionUtils.DescribedFieldFilter filter)
Finds the field matching the givenReflectionUtils.DescribedFieldFilter. Will make sure there's only one field matching the filter.- Parameters:
type- must not be null.filter- must not be null.- Returns:
- the field matching the given
ReflectionUtils.DescribedFieldFilteror null if none found. - Throws:
IllegalStateException- in case more than one matching field is found
-
findField
public static Field findField(Class<?> type, ReflectionUtils.DescribedFieldFilter filter, boolean enforceUniqueness)
Finds the field matching the givenReflectionUtils.DescribedFieldFilter. Will make sure there's only one field matching the filter in caseenforceUniquenessis true.- Parameters:
type- must not be null.filter- must not be null.enforceUniqueness- whether to enforce uniqueness of the field- Returns:
- the field matching the given
ReflectionUtils.DescribedFieldFilteror null if none found. - Throws:
IllegalStateException- if enforceUniqueness is true and more than one matching field is found
-
findRequiredField
public static Field findRequiredField(Class<?> type, String name)
Finds the field of the given name on the given type.- Parameters:
type- must not be null.name- must not be null or empty.- Throws:
IllegalArgumentException- in case the field can't be found.
-
findRequiredMethod
public static Method findRequiredMethod(Class<?> type, String name, Class<?>... parameterTypes)
Returns the method with the given name of the given class and parameter types.- Parameters:
type- must not be null.name- must not be null.parameterTypes- must not be null.- Throws:
IllegalArgumentException- in case the method cannot be resolved.
-
returnTypeAndParameters
public static Stream<Class<?>> returnTypeAndParameters(Method method)
- Parameters:
method- must not be null.
-
getPrimitiveDefault
public static Object getPrimitiveDefault(Class<?> type)
Get default value for a primitive type.- Parameters:
type- must not be null.- Returns:
- boxed primitive default value.
-
getDeclaredField
public static Field getDeclaredField(Class<?> clazz, String name) throws NoSuchFieldException
- Throws:
NoSuchFieldException
-
getPropertyValue
public static Object getPropertyValue(Object root, String propertyPath) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
- Returns:
- value of property path of root object
- Throws:
IllegalAccessExceptionInvocationTargetExceptionNoSuchMethodException
-
getContainerCLassByField
public static Class<?> getContainerCLassByField(Class<?> clazz, String fieldPath)
-
getGetterMethod
public static Method getGetterMethod(Class<?> clazz, String fieldPath) throws NoSuchMethodException
- Throws:
NoSuchMethodException
-
getContainerClassByGetter
public static Class<?> getContainerClassByGetter(Class<?> clazz, String fieldPath) throws NoSuchMethodException
- Throws:
NoSuchMethodException
-
setValue
public static Object setValue(Object root, String path, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException
-
getSetter
public static Method getSetter(Class<?> aClass, String property, Class<?>... parameterType) throws NoSuchMethodException
- Throws:
NoSuchMethodException
-
getGetter
public static Method getGetter(Class<?> aClass, String property) throws NoSuchMethodException
- Throws:
NoSuchMethodException
-
getCurrentMethod
public static Method getCurrentMethod(StackTraceElement stackTraceElement) throws ClassNotFoundException, NoSuchMethodException
- Throws:
NoSuchMethodException- getCurrentMethod(Thread.currentThread().getStackTrace()[1])ClassNotFoundException
-
getGetterName
public static String getGetterName(String property, Class<?> type)
- Parameters:
property- , Class type- Returns:
- getter of the given property, if the given property has boolean type add is to its first else add get
-
getFieldAnnotationMap
public static <T extends Annotation> Map<Field,T> getFieldAnnotationMap(Class<?> clazz, Class<T> annotationClazz, boolean includeSuperClasses)
-
getFields
public static <T extends Annotation> List<Field> getFields(Class<?> clazz, Class<T> annotationClazz, boolean includeSuperClasses)
-
fetchPropertyFields
public static Set<String> fetchPropertyFields(Set<String> allFields, String fieldName)
-
handleReflectionException
public static void handleReflectionException(Exception ex)
Handle the given reflection exception.Should only be called if no checked exception is expected to be thrown by a target method, or if an error occurs while accessing a method or field.
Throws the underlying RuntimeException or Error in case of an InvocationTargetException with such a root cause. Throws an IllegalStateException with an appropriate message or UndeclaredThrowableException otherwise.
- Parameters:
ex- the reflection exception to handle
-
handleInvocationTargetException
public static void handleInvocationTargetException(InvocationTargetException ex)
Handle the given invocation target exception. Should only be called if no checked exception is expected to be thrown by the target method.Throws the underlying RuntimeException or Error in case of such a root cause. Throws an UndeclaredThrowableException otherwise.
- Parameters:
ex- the invocation target exception to handle
-
rethrowRuntimeException
public static void rethrowRuntimeException(Throwable ex)
Rethrow the givenexception, which is presumably the target exception of anInvocationTargetException. Should only be called if no checked exception is expected to be thrown by the target method.Rethrows the underlying exception cast to a
RuntimeExceptionorErrorif appropriate; otherwise, throws anUndeclaredThrowableException.- Parameters:
ex- the exception to rethrow- Throws:
RuntimeException- the rethrown exception
-
rethrowException
public static void rethrowException(Throwable ex) throws Exception
Rethrow the givenexception, which is presumably the target exception of anInvocationTargetException. Should only be called if no checked exception is expected to be thrown by the target method.Rethrows the underlying exception cast to an
ExceptionorErrorif appropriate; otherwise, throws anUndeclaredThrowableException.- Parameters:
ex- the exception to rethrow- Throws:
Exception- the rethrown exception (in case of a checked exception)
-
accessibleConstructor
public static <T> Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes) throws NoSuchMethodException
Obtain an accessible constructor for the given class and parameters.- Parameters:
clazz- the clazz to checkparameterTypes- the parameter types of the desired constructor- Returns:
- the constructor reference
- Throws:
NoSuchMethodException- if no such constructor exists
-
makeAccessible
public static void makeAccessible(Constructor<?> ctor)
Make the given constructor accessible, explicitly setting it accessible if necessary. ThesetAccessible(true)method is only called when actually necessary, to avoid unnecessary conflicts with a JVM SecurityManager (if active).- Parameters:
ctor- the constructor to make accessible
-
findMethod
public static Method findMethod(Class<?> clazz, String name)
Attempt to find aMethodon the supplied class with the supplied name and no parameters. Searches all superclasses up toObject.Returns
nullif noMethodcan be found.- Parameters:
clazz- the class to introspectname- the name of the method- Returns:
- the Method object, or
nullif none found
-
findMethod
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes)
Attempt to find aMethodon the supplied class with the supplied name and parameter types. Searches all superclasses up toObject.Returns
nullif noMethodcan be found.- Parameters:
clazz- the class to introspectname- the name of the methodparamTypes- the parameter types of the method (may benullto indicate any signature)- Returns:
- the Method object, or
nullif none found
-
invokeMethod
public static Object invokeMethod(Method method, Object target)
Invoke the specifiedMethodagainst the supplied target object with no arguments. The target object can benullwhen invoking a staticMethod.Thrown exceptions are handled via a call to
handleReflectionException(java.lang.Exception).- Parameters:
method- the method to invoketarget- the target object to invoke the method on- Returns:
- the invocation result, if any
-
invokeMethod
public static Object invokeMethod(Method method, Object target, Object... args)
Invoke the specifiedMethodagainst the supplied target object with the supplied arguments. The target object can benullwhen invoking a staticMethod.Thrown exceptions are handled via a call to
handleReflectionException(java.lang.Exception).- Parameters:
method- the method to invoketarget- the target object to invoke the method onargs- the invocation arguments (may benull)- Returns:
- the invocation result, if any
-
declaresException
public static boolean declaresException(Method method, Class<?> exceptionType)
Determine whether the given method explicitly declares the given exception or one of its superclasses, which means that an exception of that type can be propagated as-is within a reflective invocation.- Parameters:
method- the declaring methodexceptionType- the exception to throw- Returns:
trueif the exception can be thrown as-is;falseif it needs to be wrapped
-
doWithLocalMethods
public static void doWithLocalMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc)
Perform the given callback operation on all matching methods of the given class, as locally declared or equivalent thereof (such as default methods on Java 8 based interfaces that the given class implements).- Parameters:
clazz- the class to introspectmc- the callback to invoke for each method- Throws:
IllegalStateException- if introspection fails
-
doWithMethods
public static void doWithMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc)
Perform the given callback operation on all matching methods of the given class and superclasses.The same named method occurring on subclass and superclass will appear twice, unless excluded by a
ReflectionUtils.MethodFilter.- Parameters:
clazz- the class to introspectmc- the callback to invoke for each method- Throws:
IllegalStateException- if introspection fails
-
doWithMethods
public static void doWithMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc, ReflectionUtils.MethodFilter mf)
Perform the given callback operation on all matching methods of the given class and superclasses (or given interface and super-interfaces).The same named method occurring on subclass and superclass will appear twice, unless excluded by the specified
ReflectionUtils.MethodFilter.- Parameters:
clazz- the class to introspectmc- the callback to invoke for each methodmf- the filter that determines the methods to apply the callback to- Throws:
IllegalStateException- if introspection fails
-
getAllDeclaredMethods
public static Method[] getAllDeclaredMethods(Class<?> leafClass)
Get all declared methods on the leaf class and all superclasses. Leaf class methods are included first.- Parameters:
leafClass- the class to introspect- Throws:
IllegalStateException- if introspection fails
-
getUniqueDeclaredMethods
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass)
Get the unique set of declared methods on the leaf class and all superclasses. Leaf class methods are included first and while traversing the superclass hierarchy any methods found with signatures matching a method already included are filtered out.- Parameters:
leafClass- the class to introspect- Throws:
IllegalStateException- if introspection fails
-
getUniqueDeclaredMethods
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass, ReflectionUtils.MethodFilter mf)
Get the unique set of declared methods on the leaf class and all superclasses. Leaf class methods are included first and while traversing the superclass hierarchy any methods found with signatures matching a method already included are filtered out.- Parameters:
leafClass- the class to introspectmf- the filter that determines the methods to take into account- Throws:
IllegalStateException- if introspection fails
-
getDeclaredMethods
public static Method[] getDeclaredMethods(Class<?> clazz)
Variant ofClass.getDeclaredMethods()that uses a local cache in order to avoid the JVM's SecurityManager check and new Method instances. In addition, it also includes Java 8 default methods from locally implemented interfaces, since those are effectively to be treated just like declared methods.- Parameters:
clazz- the class to introspect- Returns:
- the cached array of methods
- Throws:
IllegalStateException- if introspection fails
-
isEqualsMethod
public static boolean isEqualsMethod(Method method)
Determine whether the given method is an "equals" method.
-
isHashCodeMethod
public static boolean isHashCodeMethod(Method method)
Determine whether the given method is a "hashCode" method.
-
isToStringMethod
public static boolean isToStringMethod(Method method)
Determine whether the given method is a "toString" method.
-
isObjectMethod
public static boolean isObjectMethod(Method method)
Determine whether the given method is originally declared byObject.
-
isCglibRenamedMethod
public static boolean isCglibRenamedMethod(Method renamedMethod)
Determine whether the given method is a CGLIB 'renamed' method, following the pattern "CGLIB$methodName$0".- Parameters:
renamedMethod- the method to check
-
makeAccessible
public static void makeAccessible(Method method)
Make the given method accessible, explicitly setting it accessible if necessary. ThesetAccessible(true)method is only called when actually necessary, to avoid unnecessary conflicts with a JVM SecurityManager (if active).- Parameters:
method- the method to make accessible
-
findField
public static Field findField(Class<?> clazz, String name)
Attempt to find afieldon the suppliedClasswith the suppliedname. Searches all superclasses up toObject.- Parameters:
clazz- the class to introspectname- the name of the field- Returns:
- the corresponding Field object, or
nullif not found
-
findField
public static Field findField(Class<?> clazz, String name, Class<?> type)
Attempt to find afieldon the suppliedClasswith the suppliednameand/ortype. Searches all superclasses up toObject.- Parameters:
clazz- the class to introspectname- the name of the field (may benullif type is specified)type- the type of the field (may benullif name is specified)- Returns:
- the corresponding Field object, or
nullif not found
-
setField
public static void setField(Field field, Object target, Object value)
Set the field represented by the supplied field object on the specified target object to the specifiedvalue.In accordance with
Field.set(Object, Object)semantics, the new value is automatically unwrapped if the underlying field has a primitive type.This method does not support setting
static finalfields.Thrown exceptions are handled via a call to
handleReflectionException(Exception).- Parameters:
field- the field to settarget- the target object on which to set the fieldvalue- the value to set (may benull)
-
getField
public static Object getField(Field field, Object target)
Get the field represented by the suppliedfield objecton the specifiedtarget object. In accordance withField.get(Object)semantics, the returned value is automatically wrapped if the underlying field has a primitive type.Thrown exceptions are handled via a call to
handleReflectionException(Exception).- Parameters:
field- the field to gettarget- the target object from which to get the field- Returns:
- the field's current value
-
doWithLocalFields
public static void doWithLocalFields(Class<?> clazz, ReflectionUtils.FieldCallback fc)
Invoke the given callback on all locally declared fields in the given class.- Parameters:
clazz- the target class to analyzefc- the callback to invoke for each field- Throws:
IllegalStateException- if introspection fails
-
doWithFields
public static void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc)
Invoke the given callback on all fields in the target class, going up the class hierarchy to get all declared fields.- Parameters:
clazz- the target class to analyzefc- the callback to invoke for each field- Throws:
IllegalStateException- if introspection fails
-
doWithFields
public static void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc, ReflectionUtils.FieldFilter ff)
Invoke the given callback on all fields in the target class, going up the class hierarchy to get all declared fields.- Parameters:
clazz- the target class to analyzefc- the callback to invoke for each fieldff- the filter that determines the fields to apply the callback to- Throws:
IllegalStateException- if introspection fails
-
shallowCopyFieldState
public static void shallowCopyFieldState(Object src, Object dest)
Given the source object and the destination, which must be the same class or a subclass, copy all fields, including inherited fields. Designed to work on objects with public no-arg constructors.- Throws:
IllegalStateException- if introspection fails
-
isPublicStaticFinal
public static boolean isPublicStaticFinal(Field field)
Determine whether the given field is a "public static final" constant.- Parameters:
field- the field to check
-
makeAccessible
public static void makeAccessible(Field field)
Make the given field accessible, explicitly setting it accessible if necessary. ThesetAccessible(true)method is only called when actually necessary, to avoid unnecessary conflicts with a JVM SecurityManager (if active).- Parameters:
field- the field to make accessible
-
getSubTypeOf
public static <T> Set<Class<? extends T>> getSubTypeOf(String packagePrefix, Class<T> clazz)
-
-