Class MethodUtils
Utility reflection methods focused on methods in general rather than properties in particular.
Known Limitations: Accessing Public Methods In A Default Access SuperclassThere is an issue when invoking public methods contained in a default access superclass.
Reflection locates these methods fine and correctly assigns them as public.
However, an IllegalAccessException is thrown if the method is invoked.
MethodUtils contains a workaround for this situation.
It will attempt to call setAccessible on this method.
If this call succeeds, then the method can be invoked as normal.
This call will only succeed when the application has sufficient security privileges.
If this call fails then a warning will be logged and the method may fail.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static classRepresents the key to looking up a Method by reflection. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final Map<MethodUtils.MethodDescriptor, Reference<Method>> Stores a cache of MethodDescriptor to Method in a WeakHashMap.private static booleanIndicates whether methods should be cached for improved performance.private static final Class<?>[]An empty class arrayprivate static final Object[]An empty object arrayprivate static booleanOnly log warning about accessibility work around once. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate static voidcacheMethod(MethodUtils.MethodDescriptor md, Method method) Add a method to the cache.static intClear the method cache.static MethodgetAccessibleMethod(Class<?> clazz, Method method) Return an accessible method (that is, one that can be invoked via reflection) that implements the specified Method.static MethodgetAccessibleMethod(Class<?> clazz, String methodName, Class<?> parameterType) Return an accessible method (that is, one that can be invoked via reflection) with given name and a single parameter.static MethodgetAccessibleMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes) Return an accessible method (that is, one that can be invoked via reflection) with given name and parameters.static MethodgetAccessibleMethod(Method method) Return an accessible method (that is, one that can be invoked via reflection) that implements the specified Method.private static MethodgetAccessibleMethodFromInterfaceNest(Class<?> clazz, String methodName, Class<?>[] parameterTypes) Return an accessible method (that is, one that can be invoked via reflection) that implements the specified method, by scanning through all implemented interfaces and subinterfaces.private static MethodgetAccessibleMethodFromSuperclass(Class<?> clazz, String methodName, Class<?>[] parameterTypes) Return an accessible method (that is, one that can be invoked via reflection) by scanning through the superclasses.private static MethodReturn the method from the cache, if present.static MethodgetMatchingAccessibleMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes) Find an accessible method that matches the given name and has compatible parameters.private static floatgetObjectTransformationCost(Class<?> srcClass, Class<?> destClass) Gets the number of steps required needed to turn the source class into the destination class.static Class<?> getPrimitiveType(Class<?> wrapperType) Gets the class for the primitive type corresponding to the primitive wrapper class given.static Class<?> getPrimitiveWrapper(Class<?> primitiveType) Gets the wrapper object class for the given primitive type class.private static floatgetTotalTransformationCost(Class<?>[] srcArgs, Class<?>[] destArgs) Returns the sum of the object transformation cost for each class in the source argument list.static ObjectinvokeExactMethod(Object object, String methodName, Object arg) Invoke a method whose parameter type matches exactly the object type.static ObjectinvokeExactMethod(Object object, String methodName, Object[] args) Invoke a method whose parameter types match exactly the object types.static ObjectinvokeExactMethod(Object object, String methodName, Object[] args, Class<?>[] parameterTypes) Invoke a method whose parameter types match exactly the parameter types given.static ObjectinvokeExactStaticMethod(Class<?> objectClass, String methodName, Object arg) Invoke a static method whose parameter type matches exactly the object type.static ObjectinvokeExactStaticMethod(Class<?> objectClass, String methodName, Object[] args) Invoke a static method whose parameter types match exactly the object types.static ObjectinvokeExactStaticMethod(Class<?> objectClass, String methodName, Object[] args, Class<?>[] parameterTypes) Invoke a static method whose parameter types match exactly the parameter types given.static ObjectinvokeMethod(Object object, String methodName, Object arg) Invoke a named method whose parameter type matches the object type.static ObjectinvokeMethod(Object object, String methodName, Object[] args) Invoke a named method whose parameter type matches the object type.static ObjectinvokeMethod(Object object, String methodName, Object[] args, Class<?>[] parameterTypes) Invoke a named method whose parameter type matches the object type.static ObjectinvokeStaticMethod(Class<?> objectClass, String methodName, Object arg) Invoke a named static method whose parameter type matches the object type.static ObjectinvokeStaticMethod(Class<?> objectClass, String methodName, Object[] args) Invoke a named static method whose parameter type matches the object type.static ObjectinvokeStaticMethod(Class<?> objectClass, String methodName, Object[] args, Class<?>[] parameterTypes) Invoke a named static method whose parameter type matches the object type.static final booleanisAssignmentCompatible(Class<?> parameterType, Class<?> parameterization) Determine whether a type can be used as a parameter in a method invocation.static voidsetCacheMethods(boolean cacheMethods) Set whether methods should be cached for greater performance or not, default istrue.private static voidsetMethodAccessible(Method method) Try to make the method accessibleprivate static Object[]static Class<?> toNonPrimitiveClass(Class<?> clazz) Find a non primitive representation for given primitive class.
-
Field Details
-
loggedAccessibleWarning
private static boolean loggedAccessibleWarningOnly log warning about accessibility work around once.Note that this is broken when this class is deployed via a shared classloader in a container, as the warning message will be emitted only once, not once per webapp. However making the warning appear once per webapp means having a map keyed by context classloader which introduces nasty memory-leak problems. As this warning is really optional we can ignore this problem; only one of the webapps will get the warning in its logs but that should be good enough.
-
CACHE_METHODS
private static boolean CACHE_METHODSIndicates whether methods should be cached for improved performance.Note that when this class is deployed via a shared classloader in a container, this will affect all webapps. However making this configurable per webapp would mean having a map keyed by context classloader which may introduce memory-leak problems.
-
EMPTY_CLASS_PARAMETERS
An empty class array -
EMPTY_OBJECT_ARRAY
An empty object array -
cache
Stores a cache of MethodDescriptor to Method in a WeakHashMap.The keys into this map only ever exist as temporary variables within methods of this class, and are never exposed to users of this class. This means that the WeakHashMap is used only as a mechanism for limiting the size of the cache, ie a way to tell the garbage collector that the contents of the cache can be completely garbage-collected whenever it needs the memory. Whether this is a good approach to this problem is doubtful; something like the commons-collections LRUMap may be more appropriate (though of course selecting an appropriate size is an issue).
This static variable is safe even when this code is deployed via a shared classloader because it is keyed via a MethodDescriptor object which has a Class as one of its members and that member is used in the MethodDescriptor.equals method. So two components that load the same class via different classloaders will generate non-equal MethodDescriptor objects and hence end up with different entries in the map.
-
-
Constructor Details
-
MethodUtils
Deprecated.Will be private in 2.0.Deprecated, all methods are static.
-
-
Method Details
-
cacheMethod
Add a method to the cache.- Parameters:
md- The method descriptormethod- The method to cache
-
clearCache
public static int clearCache()Clear the method cache.- Returns:
- the number of cached methods cleared
- Since:
- 1.8.0
-
getAccessibleMethod
Return an accessible method (that is, one that can be invoked via reflection) that implements the specified Method. If no such method can be found, return
null.- Parameters:
clazz- The class of the objectmethod- The method that we wish to call- Returns:
- The accessible method
- Since:
- 1.8.0
-
getAccessibleMethod
Return an accessible method (that is, one that can be invoked via reflection) with given name and a single parameter. If no such method can be found, return
null. Basically, a convenience wrapper that constructs aClassarray for you.- Parameters:
clazz- get method from this classmethodName- get method with this nameparameterType- taking this type of parameter- Returns:
- The accessible method
-
getAccessibleMethod
public static Method getAccessibleMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes) Return an accessible method (that is, one that can be invoked via reflection) with given name and parameters. If no such method can be found, return
null. This is just a convenient wrapper forgetAccessibleMethod(Method method).- Parameters:
clazz- get method from this classmethodName- get method with this nameparameterTypes- with these parameters types- Returns:
- The accessible method
-
getAccessibleMethod
Return an accessible method (that is, one that can be invoked via reflection) that implements the specified Method. If no such method can be found, return
null.- Parameters:
method- The method that we wish to call- Returns:
- The accessible method
-
getAccessibleMethodFromInterfaceNest
private static Method getAccessibleMethodFromInterfaceNest(Class<?> clazz, String methodName, Class<?>[] parameterTypes) Return an accessible method (that is, one that can be invoked via reflection) that implements the specified method, by scanning through all implemented interfaces and subinterfaces. If no such method can be found, return
null.There isn't any good reason why this method must be private. It is because there doesn't seem any reason why other classes should call this rather than the higher level methods.
- Parameters:
clazz- Parent class for the interfaces to be checkedmethodName- Method name of the method we wish to callparameterTypes- The parameter type signatures
-
getAccessibleMethodFromSuperclass
private static Method getAccessibleMethodFromSuperclass(Class<?> clazz, String methodName, Class<?>[] parameterTypes) Return an accessible method (that is, one that can be invoked via reflection) by scanning through the superclasses. If no such method can be found, return
null.- Parameters:
clazz- Class to be checkedmethodName- Method name of the method we wish to callparameterTypes- The parameter type signatures
-
getCachedMethod
Return the method from the cache, if present.- Parameters:
md- The method descriptor- Returns:
- The cached method
-
getMatchingAccessibleMethod
public static Method getMatchingAccessibleMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes) Find an accessible method that matches the given name and has compatible parameters. Compatible parameters mean that every method parameter is assignable from the given parameters. In other words, it finds a method with the given name that will take the parameters given.
This method is slightly undeterministic since it loops through methods names and return the first matching method.
This method is used by
invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes).This method can match primitive parameter by passing in wrapper classes. For example, a
Booleanwill match a primitivebooleanparameter.- Parameters:
clazz- find method in this classmethodName- find method with this nameparameterTypes- find method with compatible parameters- Returns:
- The accessible method
-
getObjectTransformationCost
Gets the number of steps required needed to turn the source class into the destination class. This represents the number of steps in the object hierarchy graph.- Parameters:
srcClass- The source classdestClass- The destination class- Returns:
- The cost of transforming an object
-
getPrimitiveType
Gets the class for the primitive type corresponding to the primitive wrapper class given. For example, an instance ofBoolean.classreturns aboolean.class.- Parameters:
wrapperType- the- Returns:
- the primitive type class corresponding to the given wrapper class, null if no match is found
-
getPrimitiveWrapper
Gets the wrapper object class for the given primitive type class. For example, passingboolean.classreturnsBoolean.class- Parameters:
primitiveType- the primitive type class for which a match is to be found- Returns:
- the wrapper type associated with the given primitive or null if no match is found
-
getTotalTransformationCost
Returns the sum of the object transformation cost for each class in the source argument list.- Parameters:
srcArgs- The source argumentsdestArgs- The destination arguments- Returns:
- The total transformation cost
-
invokeExactMethod
public static Object invokeExactMethod(Object object, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a method whose parameter type matches exactly the object type.
This is a convenient wrapper for
invokeExactMethod(Object object,String methodName,Object [] args).- Parameters:
object- invoke method on this objectmethodName- get method with this namearg- use this argument. May be null (this will result in calling the parameterless method with namemethodName).- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection
-
invokeExactMethod
public static Object invokeExactMethod(Object object, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a method whose parameter types match exactly the object types.
This uses reflection to invoke the method obtained from a call to
getAccessibleMethod().- Parameters:
object- invoke method on this objectmethodName- get method with this nameargs- use these arguments - treat null as empty array (passing null will result in calling the parameterless method with namemethodName).- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection
-
invokeExactMethod
public static Object invokeExactMethod(Object object, String methodName, Object[] args, Class<?>[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a method whose parameter types match exactly the parameter types given.
This uses reflection to invoke the method obtained from a call to
getAccessibleMethod().- Parameters:
object- invoke method on this objectmethodName- get method with this nameargs- use these arguments - treat null as empty array (passing null will result in calling the parameterless method with namemethodName).parameterTypes- match these parameters - treat null as empty array- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection
-
invokeExactStaticMethod
public static Object invokeExactStaticMethod(Class<?> objectClass, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a static method whose parameter type matches exactly the object type.
This is a convenient wrapper for
invokeExactStaticMethod(Class objectClass,String methodName,Object [] args).- Parameters:
objectClass- invoke static method on this classmethodName- get method with this namearg- use this argument. May be null (this will result in calling the parameterless method with namemethodName).- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection- Since:
- 1.8.0
-
invokeExactStaticMethod
public static Object invokeExactStaticMethod(Class<?> objectClass, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a static method whose parameter types match exactly the object types.
This uses reflection to invoke the method obtained from a call to
getAccessibleMethod(Class, String, Class[]).- Parameters:
objectClass- invoke static method on this classmethodName- get method with this nameargs- use these arguments - treat null as empty array (passing null will result in calling the parameterless method with namemethodName).- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection- Since:
- 1.8.0
-
invokeExactStaticMethod
public static Object invokeExactStaticMethod(Class<?> objectClass, String methodName, Object[] args, Class<?>[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a static method whose parameter types match exactly the parameter types given.
This uses reflection to invoke the method obtained from a call to
getAccessibleMethod(Class, String, Class[]).- Parameters:
objectClass- invoke static method on this classmethodName- get method with this nameargs- use these arguments - treat null as empty array (passing null will result in calling the parameterless method with namemethodName).parameterTypes- match these parameters - treat null as empty array- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection- Since:
- 1.8.0
-
invokeMethod
public static Object invokeMethod(Object object, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a named method whose parameter type matches the object type.
The behavior of this method is less deterministic than
invokeExactMethod(). It loops through all methods with names that match and then executes the first it finds with compatible parameters.This method supports calls to methods taking primitive parameters via passing in wrapping classes. So, for example, a
Booleanclass would match abooleanprimitive.This is a convenient wrapper for
invokeMethod(Object object,String methodName,Object [] args).- Parameters:
object- invoke method on this objectmethodName- get method with this namearg- use this argument. May be null (this will result in calling the parameterless method with namemethodName).- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection
-
invokeMethod
public static Object invokeMethod(Object object, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a named method whose parameter type matches the object type.
The behavior of this method is less deterministic than
invokeExactMethod(Object object,String methodName,Object [] args). It loops through all methods with names that match and then executes the first it finds with compatible parameters.This method supports calls to methods taking primitive parameters via passing in wrapping classes. So, for example, a
Booleanclass would match abooleanprimitive.This is a convenient wrapper for
invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes).- Parameters:
object- invoke method on this objectmethodName- get method with this nameargs- use these arguments - treat null as empty array (passing null will result in calling the parameterless method with namemethodName).- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection
-
invokeMethod
public static Object invokeMethod(Object object, String methodName, Object[] args, Class<?>[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a named method whose parameter type matches the object type.
The behavior of this method is less deterministic than
invokeExactMethod(Object object,String methodName,Object [] args,Class[] parameterTypes). It loops through all methods with names that match and then executes the first it finds with compatible parameters.This method supports calls to methods taking primitive parameters via passing in wrapping classes. So, for example, a
Booleanclass would match abooleanprimitive.- Parameters:
object- invoke method on this objectmethodName- get method with this nameargs- use these arguments - treat null as empty array (passing null will result in calling the parameterless method with namemethodName).parameterTypes- match these parameters - treat null as empty array- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection
-
invokeStaticMethod
public static Object invokeStaticMethod(Class<?> objectClass, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a named static method whose parameter type matches the object type.
The behavior of this method is less deterministic than
invokeExactMethod(Object, String, Object[], Class[]). It loops through all methods with names that match and then executes the first it finds with compatible parameters.This method supports calls to methods taking primitive parameters via passing in wrapping classes. So, for example, a
Booleanclass would match abooleanprimitive.This is a convenient wrapper for
invokeStaticMethod(Class objectClass,String methodName,Object [] args).- Parameters:
objectClass- invoke static method on this classmethodName- get method with this namearg- use this argument. May be null (this will result in calling the parameterless method with namemethodName).- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection- Since:
- 1.8.0
-
invokeStaticMethod
public static Object invokeStaticMethod(Class<?> objectClass, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a named static method whose parameter type matches the object type.
The behavior of this method is less deterministic than
invokeExactMethod(Object object,String methodName,Object [] args). It loops through all methods with names that match and then executes the first it finds with compatible parameters.This method supports calls to methods taking primitive parameters via passing in wrapping classes. So, for example, a
Booleanclass would match abooleanprimitive.This is a convenient wrapper for
invokeStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes).- Parameters:
objectClass- invoke static method on this classmethodName- get method with this nameargs- use these arguments - treat null as empty array (passing null will result in calling the parameterless method with namemethodName).- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection- Since:
- 1.8.0
-
invokeStaticMethod
public static Object invokeStaticMethod(Class<?> objectClass, String methodName, Object[] args, Class<?>[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException Invoke a named static method whose parameter type matches the object type.
The behavior of this method is less deterministic than
invokeExactStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes). It loops through all methods with names that match and then executes the first it finds with compatible parameters.This method supports calls to methods taking primitive parameters via passing in wrapping classes. So, for example, a
Booleanclass would match abooleanprimitive.- Parameters:
objectClass- invoke static method on this classmethodName- get method with this nameargs- use these arguments - treat null as empty array (passing null will result in calling the parameterless method with namemethodName).parameterTypes- match these parameters - treat null as empty array- Returns:
- The value returned by the invoked method
- Throws:
NoSuchMethodException- if there is no such accessible methodInvocationTargetException- wraps an exception thrown by the method invokedIllegalAccessException- if the requested method is not accessible via reflection- Since:
- 1.8.0
-
isAssignmentCompatible
public static final boolean isAssignmentCompatible(Class<?> parameterType, Class<?> parameterization) Determine whether a type can be used as a parameter in a method invocation. This method handles primitive conversions correctly.
In order words, it will match a
Booleanto aboolean, aLongto along, aFloatto afloat, aIntegerto aint, and aDoubleto adouble. Now logic widening matches are allowed. For example, aLongwill not match aint.- Parameters:
parameterType- the type of parameter accepted by the methodparameterization- the type of parameter being tested- Returns:
- true if the assignment is compatible.
-
setCacheMethods
public static void setCacheMethods(boolean cacheMethods) Set whether methods should be cached for greater performance or not, default istrue.- Parameters:
cacheMethods-trueif methods should be cached for greater performance, otherwisefalse- Since:
- 1.8.0
-
setMethodAccessible
Try to make the method accessible- Parameters:
method- The source arguments
-
toArray
-
toNonPrimitiveClass
-