MethodUtils.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.lang3.reflect;

  18. import java.lang.annotation.Annotation;
  19. import java.lang.reflect.Array;
  20. import java.lang.reflect.InvocationTargetException;
  21. import java.lang.reflect.Method;
  22. import java.lang.reflect.Type;
  23. import java.lang.reflect.TypeVariable;
  24. import java.util.ArrayList;
  25. import java.util.Arrays;
  26. import java.util.Comparator;
  27. import java.util.Iterator;
  28. import java.util.LinkedHashSet;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.Objects;
  32. import java.util.Set;
  33. import java.util.TreeMap;
  34. import java.util.stream.Collectors;
  35. import java.util.stream.Stream;

  36. import org.apache.commons.lang3.ArrayUtils;
  37. import org.apache.commons.lang3.ClassUtils;
  38. import org.apache.commons.lang3.ClassUtils.Interfaces;
  39. import org.apache.commons.lang3.Validate;

  40. /**
  41.  * Utility reflection methods focused on {@link Method}s, originally from Commons BeanUtils.
  42.  * Differences from the BeanUtils version may be noted, especially where similar functionality
  43.  * already existed within Lang.
  44.  *
  45.  * <h2>Known Limitations</h2>
  46.  * <h3>Accessing Public Methods In A Default Access Superclass</h3>
  47.  * <p>There is an issue when invoking {@code public} methods contained in a default access superclass on JREs prior to 1.4.
  48.  * Reflection locates these methods fine and correctly assigns them as {@code public}.
  49.  * However, an {@link IllegalAccessException} is thrown if the method is invoked.</p>
  50.  *
  51.  * <p>{@link MethodUtils} contains a workaround for this situation.
  52.  * It will attempt to call {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} on this method.
  53.  * If this call succeeds, then the method can be invoked as normal.
  54.  * This call will only succeed when the application has sufficient security privileges.
  55.  * If this call fails then the method may fail.</p>
  56.  *
  57.  * @since 2.5
  58.  */
  59. public class MethodUtils {

  60.     private static final Comparator<Method> METHOD_BY_SIGNATURE = Comparator.comparing(Method::toString);

  61.     /**
  62.      * Returns the aggregate number of inheritance hops between assignable argument class types.  Returns -1
  63.      * if the arguments aren't assignable.  Fills a specific purpose for getMatchingMethod and is not generalized.
  64.      *
  65.      * @param fromClassArray the Class array to calculate the distance from.
  66.      * @param toClassArray the Class array to calculate the distance to.
  67.      * @return the aggregate number of inheritance hops between assignable argument class types.
  68.      */
  69.     private static int distance(final Class<?>[] fromClassArray, final Class<?>[] toClassArray) {
  70.         int answer = 0;

  71.         if (!ClassUtils.isAssignable(fromClassArray, toClassArray, true)) {
  72.             return -1;
  73.         }
  74.         for (int offset = 0; offset < fromClassArray.length; offset++) {
  75.             // Note InheritanceUtils.distance() uses different scoring system.
  76.             final Class<?> aClass = fromClassArray[offset];
  77.             final Class<?> toClass = toClassArray[offset];
  78.             if (aClass == null || aClass.equals(toClass)) {
  79.                 continue;
  80.             }
  81.             if (ClassUtils.isAssignable(aClass, toClass, true)
  82.                     && !ClassUtils.isAssignable(aClass, toClass, false)) {
  83.                 answer++;
  84.             } else {
  85.                 answer += 2;
  86.             }
  87.         }

  88.         return answer;
  89.     }

  90.     /**
  91.      * Gets 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
  92.      * {@code null}. This is just a convenience wrapper for {@link #getAccessibleMethod(Method)}.
  93.      *
  94.      * @param cls            get method from this class
  95.      * @param methodName     get method with this name
  96.      * @param parameterTypes with these parameters types
  97.      * @return The accessible method
  98.      */
  99.     public static Method getAccessibleMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes) {
  100.         return getAccessibleMethod(getMethodObject(cls, methodName, parameterTypes));
  101.     }

  102.     /**
  103.      * Gets an accessible method (that is, one that can be invoked via
  104.      * reflection) that implements the specified Method. If no such method
  105.      * can be found, return {@code null}.
  106.      *
  107.      * @param method The method that we wish to call, may be null.
  108.      * @return The accessible method
  109.      */
  110.     public static Method getAccessibleMethod(Method method) {
  111.         if (!MemberUtils.isAccessible(method)) {
  112.             return null;
  113.         }
  114.         // If the declaring class is public, we are done
  115.         final Class<?> cls = method.getDeclaringClass();
  116.         if (ClassUtils.isPublic(cls)) {
  117.             return method;
  118.         }
  119.         final String methodName = method.getName();
  120.         final Class<?>[] parameterTypes = method.getParameterTypes();

  121.         // Check the implemented interfaces and subinterfaces
  122.         method = getAccessibleMethodFromInterfaceNest(cls, methodName,
  123.                 parameterTypes);

  124.         // Check the superclass chain
  125.         if (method == null) {
  126.             method = getAccessibleMethodFromSuperclass(cls, methodName,
  127.                     parameterTypes);
  128.         }
  129.         return method;
  130.     }

  131.     /**
  132.      * Gets an accessible method (that is, one that can be invoked via
  133.      * reflection) that implements the specified method, by scanning through
  134.      * all implemented interfaces and subinterfaces. If no such method
  135.      * can be found, return {@code null}.
  136.      *
  137.      * <p>There isn't any good reason why this method must be {@code private}.
  138.      * It is because there doesn't seem any reason why other classes should
  139.      * call this rather than the higher level methods.</p>
  140.      *
  141.      * @param cls Parent class for the interfaces to be checked
  142.      * @param methodName Method name of the method we wish to call
  143.      * @param parameterTypes The parameter type signatures
  144.      * @return the accessible method or {@code null} if not found
  145.      */
  146.     private static Method getAccessibleMethodFromInterfaceNest(Class<?> cls,
  147.             final String methodName, final Class<?>... parameterTypes) {
  148.         // Search up the superclass chain
  149.         for (; cls != null; cls = cls.getSuperclass()) {

  150.             // Check the implemented interfaces of the parent class
  151.             final Class<?>[] interfaces = cls.getInterfaces();
  152.             for (final Class<?> anInterface : interfaces) {
  153.                 // Is this interface public?
  154.                 if (!ClassUtils.isPublic(anInterface)) {
  155.                     continue;
  156.                 }
  157.                 // Does the method exist on this interface?
  158.                 try {
  159.                     return anInterface.getDeclaredMethod(methodName,
  160.                             parameterTypes);
  161.                 } catch (final NoSuchMethodException ignored) {
  162.                     /*
  163.                      * Swallow, if no method is found after the loop then this
  164.                      * method returns null.
  165.                      */
  166.                 }
  167.                 // Recursively check our parent interfaces
  168.                 final Method method = getAccessibleMethodFromInterfaceNest(anInterface,
  169.                         methodName, parameterTypes);
  170.                 if (method != null) {
  171.                     return method;
  172.                 }
  173.             }
  174.         }
  175.         return null;
  176.     }

  177.     /**
  178.      * Gets an accessible method (that is, one that can be invoked via
  179.      * reflection) by scanning through the superclasses. If no such method
  180.      * can be found, return {@code null}.
  181.      *
  182.      * @param cls Class to be checked
  183.      * @param methodName Method name of the method we wish to call
  184.      * @param parameterTypes The parameter type signatures
  185.      * @return the accessible method or {@code null} if not found
  186.      */
  187.     private static Method getAccessibleMethodFromSuperclass(final Class<?> cls,
  188.             final String methodName, final Class<?>... parameterTypes) {
  189.         Class<?> parentClass = cls.getSuperclass();
  190.         while (parentClass != null) {
  191.             if (ClassUtils.isPublic(parentClass)) {
  192.                 return getMethodObject(parentClass, methodName, parameterTypes);
  193.             }
  194.             parentClass = parentClass.getSuperclass();
  195.         }
  196.         return null;
  197.     }

  198.     /**
  199.      * Gets a combination of {@link ClassUtils#getAllSuperclasses(Class)} and
  200.      * {@link ClassUtils#getAllInterfaces(Class)}, one from superclasses, one
  201.      * from interfaces, and so on in a breadth first way.
  202.      *
  203.      * @param cls  the class to look up, may be {@code null}
  204.      * @return the combined {@link List} of superclasses and interfaces in order
  205.      * going up from this one
  206.      *  {@code null} if null input
  207.      */
  208.     private static List<Class<?>> getAllSuperclassesAndInterfaces(final Class<?> cls) {
  209.         if (cls == null) {
  210.             return null;
  211.         }

  212.         final List<Class<?>> allSuperClassesAndInterfaces = new ArrayList<>();
  213.         final List<Class<?>> allSuperclasses = ClassUtils.getAllSuperclasses(cls);
  214.         int superClassIndex = 0;
  215.         final List<Class<?>> allInterfaces = ClassUtils.getAllInterfaces(cls);
  216.         int interfaceIndex = 0;
  217.         while (interfaceIndex < allInterfaces.size() ||
  218.                 superClassIndex < allSuperclasses.size()) {
  219.             final Class<?> acls;
  220.             if (interfaceIndex >= allInterfaces.size()) {
  221.                 acls = allSuperclasses.get(superClassIndex++);
  222.             } else if (superClassIndex >= allSuperclasses.size() || !(superClassIndex < interfaceIndex)) {
  223.                 acls = allInterfaces.get(interfaceIndex++);
  224.             } else {
  225.                 acls = allSuperclasses.get(superClassIndex++);
  226.             }
  227.             allSuperClassesAndInterfaces.add(acls);
  228.         }
  229.         return allSuperClassesAndInterfaces;
  230.     }

  231.     /**
  232.      * Gets the annotation object with the given annotation type that is present on the given method
  233.      * or optionally on any equivalent method in super classes and interfaces. Returns null if the annotation
  234.      * type was not present.
  235.      *
  236.      * <p>Stops searching for an annotation once the first annotation of the specified type has been
  237.      * found. Additional annotations of the specified type will be silently ignored.</p>
  238.      * @param <A>
  239.      *            the annotation type
  240.      * @param method
  241.      *            the {@link Method} to query, may be null.
  242.      * @param annotationCls
  243.      *            the {@link Annotation} to check if is present on the method
  244.      * @param searchSupers
  245.      *            determines if a lookup in the entire inheritance hierarchy of the given class is performed
  246.      *            if the annotation was not directly present
  247.      * @param ignoreAccess
  248.      *            determines if underlying method has to be accessible
  249.      * @return the first matching annotation, or {@code null} if not found
  250.      * @throws NullPointerException if either the method or annotation class is {@code null}
  251.      * @since 3.6
  252.      */
  253.     public static <A extends Annotation> A getAnnotation(final Method method, final Class<A> annotationCls,
  254.                                                          final boolean searchSupers, final boolean ignoreAccess) {

  255.         Objects.requireNonNull(method, "method");
  256.         Objects.requireNonNull(annotationCls, "annotationCls");
  257.         if (!ignoreAccess && !MemberUtils.isAccessible(method)) {
  258.             return null;
  259.         }

  260.         A annotation = method.getAnnotation(annotationCls);

  261.         if (annotation == null && searchSupers) {
  262.             final Class<?> mcls = method.getDeclaringClass();
  263.             final List<Class<?>> classes = getAllSuperclassesAndInterfaces(mcls);
  264.             for (final Class<?> acls : classes) {
  265.                 final Method equivalentMethod = ignoreAccess ? getMatchingMethod(acls, method.getName(), method.getParameterTypes())
  266.                         : getMatchingAccessibleMethod(acls, method.getName(), method.getParameterTypes());
  267.                 if (equivalentMethod != null) {
  268.                     annotation = equivalentMethod.getAnnotation(annotationCls);
  269.                     if (annotation != null) {
  270.                         break;
  271.                     }
  272.                 }
  273.             }
  274.         }

  275.         return annotation;
  276.     }

  277.     /**
  278.      * Gets an accessible method that matches the given name and has compatible parameters.
  279.      * Compatible parameters mean that every method parameter is assignable from
  280.      * the given parameters.
  281.      * In other words, it finds a method with the given name
  282.      * that will take the parameters given.
  283.      *
  284.      * <p>This method is used by
  285.      * {@link
  286.      * #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}.
  287.      * </p>
  288.      *
  289.      * <p>This method can match primitive parameter by passing in wrapper classes.
  290.      * For example, a {@link Boolean} will match a primitive {@code boolean}
  291.      * parameter.
  292.      * </p>
  293.      *
  294.      * @param cls find method in this class
  295.      * @param methodName find method with this name
  296.      * @param parameterTypes find method with most compatible parameters
  297.      * @return The accessible method
  298.      */
  299.     public static Method getMatchingAccessibleMethod(final Class<?> cls,
  300.         final String methodName, final Class<?>... parameterTypes) {
  301.         final Method candidate = getMethodObject(cls, methodName, parameterTypes);
  302.         if (candidate != null) {
  303.             return MemberUtils.setAccessibleWorkaround(candidate);
  304.         }
  305.         // search through all methods
  306.         final Method[] methods = cls.getMethods();
  307.         final List<Method> matchingMethods = Stream.of(methods)
  308.             .filter(method -> method.getName().equals(methodName) && MemberUtils.isMatchingMethod(method, parameterTypes)).collect(Collectors.toList());

  309.         // Sort methods by signature to force deterministic result
  310.         matchingMethods.sort(METHOD_BY_SIGNATURE);

  311.         Method bestMatch = null;
  312.         for (final Method method : matchingMethods) {
  313.             // get accessible version of method
  314.             final Method accessibleMethod = getAccessibleMethod(method);
  315.             if (accessibleMethod != null && (bestMatch == null || MemberUtils.compareMethodFit(accessibleMethod, bestMatch, parameterTypes) < 0)) {
  316.                 bestMatch = accessibleMethod;
  317.             }
  318.         }
  319.         if (bestMatch != null) {
  320.             MemberUtils.setAccessibleWorkaround(bestMatch);
  321.         }

  322.         if (bestMatch != null && bestMatch.isVarArgs() && bestMatch.getParameterTypes().length > 0 && parameterTypes.length > 0) {
  323.             final Class<?>[] methodParameterTypes = bestMatch.getParameterTypes();
  324.             final Class<?> methodParameterComponentType = methodParameterTypes[methodParameterTypes.length - 1].getComponentType();
  325.             final String methodParameterComponentTypeName = ClassUtils.primitiveToWrapper(methodParameterComponentType).getName();

  326.             final Class<?> lastParameterType = parameterTypes[parameterTypes.length - 1];
  327.             final String parameterTypeName = lastParameterType == null ? null : lastParameterType.getName();
  328.             final String parameterTypeSuperClassName = lastParameterType == null ? null : lastParameterType.getSuperclass().getName();

  329.             if (parameterTypeName != null && parameterTypeSuperClassName != null && !methodParameterComponentTypeName.equals(parameterTypeName)
  330.                 && !methodParameterComponentTypeName.equals(parameterTypeSuperClassName)) {
  331.                 return null;
  332.             }
  333.         }

  334.         return bestMatch;
  335.     }

  336.     /**
  337.      * Gets a method whether or not it's accessible. If no such method
  338.      * can be found, return {@code null}.
  339.      *
  340.      * @param cls The class that will be subjected to the method search
  341.      * @param methodName The method that we wish to call
  342.      * @param parameterTypes Argument class types
  343.      * @throws IllegalStateException if there is no unique result
  344.      * @throws NullPointerException if the class is {@code null}
  345.      * @return The method
  346.      *
  347.      * @since 3.5
  348.      */
  349.     public static Method getMatchingMethod(final Class<?> cls, final String methodName,
  350.             final Class<?>... parameterTypes) {
  351.         Objects.requireNonNull(cls, "cls");
  352.         Validate.notEmpty(methodName, "methodName");

  353.         final List<Method> methods = Stream.of(cls.getDeclaredMethods())
  354.                 .filter(method -> method.getName().equals(methodName))
  355.                 .collect(Collectors.toList());

  356.         ClassUtils.getAllSuperclasses(cls).stream()
  357.                 .map(Class::getDeclaredMethods)
  358.                 .flatMap(Stream::of)
  359.                 .filter(method -> method.getName().equals(methodName))
  360.                 .forEach(methods::add);

  361.         for (final Method method : methods) {
  362.             if (Arrays.deepEquals(method.getParameterTypes(), parameterTypes)) {
  363.                 return method;
  364.             }
  365.         }

  366.         final TreeMap<Integer, List<Method>> candidates = new TreeMap<>();

  367.         methods.stream()
  368.                 .filter(method -> ClassUtils.isAssignable(parameterTypes, method.getParameterTypes(), true))
  369.                 .forEach(method -> {
  370.                     final int distance = distance(parameterTypes, method.getParameterTypes());
  371.                     final List<Method> candidatesAtDistance = candidates.computeIfAbsent(distance, k -> new ArrayList<>());
  372.                     candidatesAtDistance.add(method);
  373.                 });

  374.         if (candidates.isEmpty()) {
  375.             return null;
  376.         }

  377.         final List<Method> bestCandidates = candidates.values().iterator().next();
  378.         if (bestCandidates.size() == 1 || !Objects.equals(bestCandidates.get(0).getDeclaringClass(),
  379.                 bestCandidates.get(1).getDeclaringClass())) {
  380.             return bestCandidates.get(0);
  381.         }

  382.         throw new IllegalStateException(
  383.                 String.format("Found multiple candidates for method %s on class %s : %s",
  384.                         methodName + Stream.of(parameterTypes).map(String::valueOf).collect(Collectors.joining(",", "(", ")")),
  385.                         cls.getName(),
  386.                         bestCandidates.stream().map(Method::toString).collect(Collectors.joining(",", "[", "]")))
  387.         );
  388.     }

  389.     /**
  390.      * Gets a Method or null if a {@link Class#getMethod(String, Class...) documented} exception is thrown.
  391.      *
  392.      * @param cls Receiver for {@link Class#getMethod(String, Class...)}.
  393.      * @param name the name of the method
  394.      * @param parameterTypes the list of parameters
  395.      * @return a Method or null.
  396.      * @since 3.15.0
  397.      * @see Class#getMethod(String, Class...)
  398.      */
  399.     public static Method getMethodObject(final Class<?> cls, final String name, final Class<?>... parameterTypes) {
  400.         try {
  401.             return cls.getMethod(name, parameterTypes);
  402.         } catch (final NoSuchMethodException | SecurityException e) {
  403.             return null;
  404.         }
  405.     }

  406.     /**
  407.      * Gets all class level public methods of the given class that are annotated with the given annotation.
  408.      * @param cls
  409.      *            the {@link Class} to query
  410.      * @param annotationCls
  411.      *            the {@link Annotation} that must be present on a method to be matched
  412.      * @return a list of Methods (possibly empty).
  413.      * @throws NullPointerException
  414.      *            if the class or annotation are {@code null}
  415.      * @since 3.4
  416.      */
  417.     public static List<Method> getMethodsListWithAnnotation(final Class<?> cls, final Class<? extends Annotation> annotationCls) {
  418.         return getMethodsListWithAnnotation(cls, annotationCls, false, false);
  419.     }

  420.     /**
  421.      * Gets all methods of the given class that are annotated with the given annotation.
  422.      *
  423.      * @param cls
  424.      *            the {@link Class} to query
  425.      * @param annotationCls
  426.      *            the {@link Annotation} that must be present on a method to be matched
  427.      * @param searchSupers
  428.      *            determines if a lookup in the entire inheritance hierarchy of the given class should be performed
  429.      * @param ignoreAccess
  430.      *            determines if non-public methods should be considered
  431.      * @return a list of Methods (possibly empty).
  432.      * @throws NullPointerException if either the class or annotation class is {@code null}
  433.      * @since 3.6
  434.      */
  435.     public static List<Method> getMethodsListWithAnnotation(final Class<?> cls,
  436.                                                             final Class<? extends Annotation> annotationCls,
  437.                                                             final boolean searchSupers, final boolean ignoreAccess) {

  438.         Objects.requireNonNull(cls, "cls");
  439.         Objects.requireNonNull(annotationCls, "annotationCls");
  440.         final List<Class<?>> classes = searchSupers ? getAllSuperclassesAndInterfaces(cls) : new ArrayList<>();
  441.         classes.add(0, cls);
  442.         final List<Method> annotatedMethods = new ArrayList<>();
  443.         classes.forEach(acls -> {
  444.             final Method[] methods = ignoreAccess ? acls.getDeclaredMethods() : acls.getMethods();
  445.             Stream.of(methods).filter(method -> method.isAnnotationPresent(annotationCls)).forEachOrdered(annotatedMethods::add);
  446.         });
  447.         return annotatedMethods;
  448.     }

  449.     /**
  450.      * Gets all class level public methods of the given class that are annotated with the given annotation.
  451.      *
  452.      * @param cls
  453.      *            the {@link Class} to query
  454.      * @param annotationCls
  455.      *            the {@link java.lang.annotation.Annotation} that must be present on a method to be matched
  456.      * @return an array of Methods (possibly empty).
  457.      * @throws NullPointerException if the class or annotation are {@code null}
  458.      * @since 3.4
  459.      */
  460.     public static Method[] getMethodsWithAnnotation(final Class<?> cls, final Class<? extends Annotation> annotationCls) {
  461.         return getMethodsWithAnnotation(cls, annotationCls, false, false);
  462.     }

  463.     /**
  464.      * Gets all methods of the given class that are annotated with the given annotation.
  465.      *
  466.      * @param cls
  467.      *            the {@link Class} to query
  468.      * @param annotationCls
  469.      *            the {@link java.lang.annotation.Annotation} that must be present on a method to be matched
  470.      * @param searchSupers
  471.      *            determines if a lookup in the entire inheritance hierarchy of the given class should be performed
  472.      * @param ignoreAccess
  473.      *            determines if non-public methods should be considered
  474.      * @return an array of Methods (possibly empty).
  475.      * @throws NullPointerException if the class or annotation are {@code null}
  476.      * @since 3.6
  477.      */
  478.     public static Method[] getMethodsWithAnnotation(final Class<?> cls, final Class<? extends Annotation> annotationCls,
  479.         final boolean searchSupers, final boolean ignoreAccess) {
  480.         return getMethodsListWithAnnotation(cls, annotationCls, searchSupers, ignoreAccess).toArray(ArrayUtils.EMPTY_METHOD_ARRAY);
  481.     }

  482.     /**
  483.      * Gets the hierarchy of overridden methods down to {@code result} respecting generics.
  484.      *
  485.      * @param method lowest to consider
  486.      * @param interfacesBehavior whether to search interfaces, {@code null} {@code implies} false
  487.      * @return a {@code Set<Method>} in ascending order from sub- to superclass
  488.      * @throws NullPointerException if the specified method is {@code null}
  489.      * @since 3.2
  490.      */
  491.     public static Set<Method> getOverrideHierarchy(final Method method, final Interfaces interfacesBehavior) {
  492.         Objects.requireNonNull(method, "method");
  493.         final Set<Method> result = new LinkedHashSet<>();
  494.         result.add(method);

  495.         final Class<?>[] parameterTypes = method.getParameterTypes();

  496.         final Class<?> declaringClass = method.getDeclaringClass();

  497.         final Iterator<Class<?>> hierarchy = ClassUtils.hierarchy(declaringClass, interfacesBehavior).iterator();
  498.         //skip the declaring class :P
  499.         hierarchy.next();
  500.         hierarchyTraversal: while (hierarchy.hasNext()) {
  501.             final Class<?> c = hierarchy.next();
  502.             final Method m = getMatchingAccessibleMethod(c, method.getName(), parameterTypes);
  503.             if (m == null) {
  504.                 continue;
  505.             }
  506.             if (Arrays.equals(m.getParameterTypes(), parameterTypes)) {
  507.                 // matches without generics
  508.                 result.add(m);
  509.                 continue;
  510.             }
  511.             // necessary to get arguments every time in the case that we are including interfaces
  512.             final Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(declaringClass, m.getDeclaringClass());
  513.             for (int i = 0; i < parameterTypes.length; i++) {
  514.                 final Type childType = TypeUtils.unrollVariables(typeArguments, method.getGenericParameterTypes()[i]);
  515.                 final Type parentType = TypeUtils.unrollVariables(typeArguments, m.getGenericParameterTypes()[i]);
  516.                 if (!TypeUtils.equals(childType, parentType)) {
  517.                     continue hierarchyTraversal;
  518.                 }
  519.             }
  520.             result.add(m);
  521.         }
  522.         return result;
  523.     }

  524.     /**
  525.      * Gets an array of arguments in the canonical form, given an arguments array passed to a varargs method,
  526.      * for example an array with the declared number of parameters, and whose last parameter is an array of the varargs type.
  527.      *
  528.      * @param args the array of arguments passed to the varags method
  529.      * @param methodParameterTypes the declared array of method parameter types
  530.      * @return an array of the variadic arguments passed to the method
  531.      * @since 3.5
  532.      */
  533.     static Object[] getVarArgs(final Object[] args, final Class<?>[] methodParameterTypes) {
  534.         if (args.length == methodParameterTypes.length
  535.                 && (args[args.length - 1] == null || args[args.length - 1].getClass().equals(methodParameterTypes[methodParameterTypes.length - 1]))) {
  536.             // The args array is already in the canonical form for the method.
  537.             return args;
  538.         }

  539.         // Construct a new array matching the method's declared parameter types.
  540.         // Copy the normal (non-varargs) parameters
  541.         final Object[] newArgs = ArrayUtils.arraycopy(args, 0, 0, methodParameterTypes.length - 1, () -> new Object[methodParameterTypes.length]);

  542.         // Construct a new array for the variadic parameters
  543.         final Class<?> varArgComponentType = methodParameterTypes[methodParameterTypes.length - 1].getComponentType();
  544.         final int varArgLength = args.length - methodParameterTypes.length + 1;

  545.         // Copy the variadic arguments into the varargs array.
  546.         Object varArgsArray = ArrayUtils.arraycopy(args, methodParameterTypes.length - 1, 0, varArgLength,
  547.                 s -> Array.newInstance(ClassUtils.primitiveToWrapper(varArgComponentType), varArgLength));

  548.         if (varArgComponentType.isPrimitive()) {
  549.             // unbox from wrapper type to primitive type
  550.             varArgsArray = ArrayUtils.toPrimitive(varArgsArray);
  551.         }

  552.         // Store the varargs array in the last position of the array to return
  553.         newArgs[methodParameterTypes.length - 1] = varArgsArray;

  554.         // Return the canonical varargs array.
  555.         return newArgs;
  556.     }

  557.     /**
  558.      * Invokes a method whose parameter types match exactly the object
  559.      * types.
  560.      *
  561.      * <p>This uses reflection to invoke the method obtained from a call to
  562.      * {@link #getAccessibleMethod}(Class, String, Class[])}.</p>
  563.      *
  564.      * @param object invoke method on this object
  565.      * @param methodName get method with this name
  566.      * @return The value returned by the invoked method
  567.      *
  568.      * @throws NoSuchMethodException if there is no such accessible method
  569.      * @throws InvocationTargetException wraps an exception thrown by the
  570.      *  method invoked
  571.      * @throws IllegalAccessException if the requested method is not accessible
  572.      *  via reflection
  573.      *
  574.      * @since 3.4
  575.      */
  576.     public static Object invokeExactMethod(final Object object, final String methodName) throws NoSuchMethodException,
  577.             IllegalAccessException, InvocationTargetException {
  578.         return invokeExactMethod(object, methodName, ArrayUtils.EMPTY_OBJECT_ARRAY, null);
  579.     }

  580.     /**
  581.      * Invokes a method with no parameters.
  582.      *
  583.      * <p>This uses reflection to invoke the method obtained from a call to
  584.      * {@link #getAccessibleMethod}(Class, String, Class[])}.</p>
  585.      *
  586.      * @param object invoke method on this object
  587.      * @param methodName get method with this name
  588.      * @param args use these arguments - treat null as empty array
  589.      * @return The value returned by the invoked method
  590.      *
  591.      * @throws NoSuchMethodException if there is no such accessible method
  592.      * @throws InvocationTargetException wraps an exception thrown by the
  593.      *  method invoked
  594.      * @throws IllegalAccessException if the requested method is not accessible
  595.      *  via reflection
  596.      * @throws NullPointerException if the object or method name are {@code null}
  597.      */
  598.     public static Object invokeExactMethod(final Object object, final String methodName,
  599.             Object... args) throws NoSuchMethodException,
  600.             IllegalAccessException, InvocationTargetException {
  601.         args = ArrayUtils.nullToEmpty(args);
  602.         return invokeExactMethod(object, methodName, args, ClassUtils.toClass(args));
  603.     }

  604.     /**
  605.      * Invokes a method whose parameter types match exactly the parameter
  606.      * types given.
  607.      *
  608.      * <p>This uses reflection to invoke the method obtained from a call to
  609.      * {@link #getAccessibleMethod(Class, String, Class[])}.</p>
  610.      *
  611.      * @param object invoke method on this object
  612.      * @param methodName get method with this name
  613.      * @param args use these arguments - treat null as empty array
  614.      * @param parameterTypes match these parameters - treat {@code null} as empty array
  615.      * @return The value returned by the invoked method
  616.      *
  617.      * @throws NoSuchMethodException if there is no such accessible method
  618.      * @throws InvocationTargetException wraps an exception thrown by the
  619.      *  method invoked
  620.      * @throws IllegalAccessException if the requested method is not accessible
  621.      *  via reflection
  622.      * @throws NullPointerException if the object or method name are {@code null}
  623.      */
  624.     public static Object invokeExactMethod(final Object object, final String methodName, Object[] args, Class<?>[] parameterTypes)
  625.         throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
  626.         Objects.requireNonNull(object, "object");
  627.         args = ArrayUtils.nullToEmpty(args);
  628.         parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
  629.         final Class<?> cls = object.getClass();
  630.         final Method method = getAccessibleMethod(cls, methodName, parameterTypes);
  631.         if (method == null) {
  632.             throw new NoSuchMethodException("No such accessible method: " + methodName + "() on object: " + cls.getName());
  633.         }
  634.         return method.invoke(object, args);
  635.     }

  636.     /**
  637.      * Invokes a {@code static} method whose parameter types match exactly the object
  638.      * types.
  639.      *
  640.      * <p>This uses reflection to invoke the method obtained from a call to
  641.      * {@link #getAccessibleMethod(Class, String, Class[])}.</p>
  642.      *
  643.      * @param cls invoke static method on this class
  644.      * @param methodName get method with this name
  645.      * @param args use these arguments - treat {@code null} as empty array
  646.      * @return The value returned by the invoked method
  647.      *
  648.      * @throws NoSuchMethodException if there is no such accessible method
  649.      * @throws InvocationTargetException wraps an exception thrown by the
  650.      *  method invoked
  651.      * @throws IllegalAccessException if the requested method is not accessible
  652.      *  via reflection
  653.      */
  654.     public static Object invokeExactStaticMethod(final Class<?> cls, final String methodName,
  655.             Object... args) throws NoSuchMethodException,
  656.             IllegalAccessException, InvocationTargetException {
  657.         args = ArrayUtils.nullToEmpty(args);
  658.         return invokeExactStaticMethod(cls, methodName, args, ClassUtils.toClass(args));
  659.     }

  660.     /**
  661.      * Invokes a {@code static} method whose parameter types match exactly the parameter
  662.      * types given.
  663.      *
  664.      * <p>This uses reflection to invoke the method obtained from a call to
  665.      * {@link #getAccessibleMethod(Class, String, Class[])}.</p>
  666.      *
  667.      * @param cls invoke static method on this class
  668.      * @param methodName get method with this name
  669.      * @param args use these arguments - treat {@code null} as empty array
  670.      * @param parameterTypes match these parameters - treat {@code null} as empty array
  671.      * @return The value returned by the invoked method
  672.      *
  673.      * @throws NoSuchMethodException if there is no such accessible method
  674.      * @throws InvocationTargetException wraps an exception thrown by the
  675.      *  method invoked
  676.      * @throws IllegalAccessException if the requested method is not accessible
  677.      *  via reflection
  678.      */
  679.     public static Object invokeExactStaticMethod(final Class<?> cls, final String methodName,
  680.             Object[] args, Class<?>[] parameterTypes)
  681.             throws NoSuchMethodException, IllegalAccessException,
  682.             InvocationTargetException {
  683.         args = ArrayUtils.nullToEmpty(args);
  684.         parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
  685.         final Method method = getAccessibleMethod(cls, methodName, parameterTypes);
  686.         if (method == null) {
  687.             throw new NoSuchMethodException("No such accessible method: "
  688.                     + methodName + "() on class: " + cls.getName());
  689.         }
  690.         return method.invoke(null, args);
  691.     }

  692.     /**
  693.      * Invokes a named method without parameters.
  694.      *
  695.      * <p>This is a convenient wrapper for
  696.      * {@link #invokeMethod(Object object, boolean forceAccess, String methodName, Object[] args, Class[] parameterTypes)}.
  697.      * </p>
  698.      *
  699.      * @param object invoke method on this object
  700.      * @param forceAccess force access to invoke method even if it's not accessible
  701.      * @param methodName get method with this name
  702.      * @return The value returned by the invoked method
  703.      *
  704.      * @throws NoSuchMethodException if there is no such accessible method
  705.      * @throws InvocationTargetException wraps an exception thrown by the method invoked
  706.      * @throws IllegalAccessException if the requested method is not accessible via reflection
  707.      *
  708.      * @since 3.5
  709.      */
  710.     public static Object invokeMethod(final Object object, final boolean forceAccess, final String methodName)
  711.             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
  712.         return invokeMethod(object, forceAccess, methodName, ArrayUtils.EMPTY_OBJECT_ARRAY, null);
  713.     }

  714.     /**
  715.      * Invokes a named method whose parameter type matches the object type.
  716.      *
  717.      * <p>This method supports calls to methods taking primitive parameters
  718.      * via passing in wrapping classes. So, for example, a {@link Boolean} object
  719.      * would match a {@code boolean} primitive.</p>
  720.      *
  721.      * <p>This is a convenient wrapper for
  722.      * {@link #invokeMethod(Object object, boolean forceAccess, String methodName, Object[] args, Class[] parameterTypes)}.
  723.      * </p>
  724.      *
  725.      * @param object invoke method on this object
  726.      * @param forceAccess force access to invoke method even if it's not accessible
  727.      * @param methodName get method with this name
  728.      * @param args use these arguments - treat null as empty array
  729.      * @return The value returned by the invoked method
  730.      *
  731.      * @throws NoSuchMethodException if there is no such accessible method
  732.      * @throws InvocationTargetException wraps an exception thrown by the method invoked
  733.      * @throws IllegalAccessException if the requested method is not accessible via reflection
  734.      * @throws NullPointerException if the object or method name are {@code null}
  735.      * @since 3.5
  736.      */
  737.     public static Object invokeMethod(final Object object, final boolean forceAccess, final String methodName,
  738.             Object... args) throws NoSuchMethodException,
  739.             IllegalAccessException, InvocationTargetException {
  740.         args = ArrayUtils.nullToEmpty(args);
  741.         return invokeMethod(object, forceAccess, methodName, args, ClassUtils.toClass(args));
  742.     }

  743.     /**
  744.      * Invokes a named method whose parameter type matches the object type.
  745.      *
  746.      * <p>This method supports calls to methods taking primitive parameters
  747.      * via passing in wrapping classes. So, for example, a {@link Boolean} object
  748.      * would match a {@code boolean} primitive.</p>
  749.      *
  750.      * @param object invoke method on this object
  751.      * @param forceAccess force access to invoke method even if it's not accessible
  752.      * @param methodName get method with this name
  753.      * @param args use these arguments - treat null as empty array
  754.      * @param parameterTypes match these parameters - treat null as empty array
  755.      * @return The value returned by the invoked method
  756.      *
  757.      * @throws NoSuchMethodException if there is no such accessible method
  758.      * @throws InvocationTargetException wraps an exception thrown by the method invoked
  759.      * @throws IllegalAccessException if the requested method is not accessible via reflection
  760.      * @throws NullPointerException if the object or method name are {@code null}
  761.      * @since 3.5
  762.      */
  763.     public static Object invokeMethod(final Object object, final boolean forceAccess, final String methodName, Object[] args, Class<?>[] parameterTypes)
  764.         throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
  765.         Objects.requireNonNull(object, "object");
  766.         parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
  767.         args = ArrayUtils.nullToEmpty(args);

  768.         final String messagePrefix;
  769.         final Method method;

  770.         final Class<? extends Object> cls = object.getClass();
  771.         if (forceAccess) {
  772.             messagePrefix = "No such method: ";
  773.             method = getMatchingMethod(cls, methodName, parameterTypes);
  774.             if (method != null && !method.isAccessible()) {
  775.                 method.setAccessible(true);
  776.             }
  777.         } else {
  778.             messagePrefix = "No such accessible method: ";
  779.             method = getMatchingAccessibleMethod(cls, methodName, parameterTypes);
  780.         }

  781.         if (method == null) {
  782.             throw new NoSuchMethodException(messagePrefix + methodName + "() on object: " + cls.getName());
  783.         }
  784.         args = toVarArgs(method, args);

  785.         return method.invoke(object, args);
  786.     }

  787.     /**
  788.      * Invokes a named method without parameters.
  789.      *
  790.      * <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
  791.      *
  792.      * <p>This is a convenient wrapper for
  793.      * {@link #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}.
  794.      * </p>
  795.      *
  796.      * @param object invoke method on this object
  797.      * @param methodName get method with this name
  798.      * @return The value returned by the invoked method
  799.      *
  800.      * @throws NoSuchMethodException if there is no such accessible method
  801.      * @throws InvocationTargetException wraps an exception thrown by the method invoked
  802.      * @throws IllegalAccessException if the requested method is not accessible via reflection
  803.      *
  804.      *  @since 3.4
  805.      */
  806.     public static Object invokeMethod(final Object object, final String methodName) throws NoSuchMethodException,
  807.             IllegalAccessException, InvocationTargetException {
  808.         return invokeMethod(object, methodName, ArrayUtils.EMPTY_OBJECT_ARRAY, null);
  809.     }

  810.     /**
  811.      * Invokes a named method whose parameter type matches the object type.
  812.      *
  813.      * <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
  814.      *
  815.      * <p>This method supports calls to methods taking primitive parameters
  816.      * via passing in wrapping classes. So, for example, a {@link Boolean} object
  817.      * would match a {@code boolean} primitive.</p>
  818.      *
  819.      * <p>This is a convenient wrapper for
  820.      * {@link #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}.
  821.      * </p>
  822.      *
  823.      * @param object invoke method on this object
  824.      * @param methodName get method with this name
  825.      * @param args use these arguments - treat null as empty array
  826.      * @return The value returned by the invoked method
  827.      *
  828.      * @throws NoSuchMethodException if there is no such accessible method
  829.      * @throws InvocationTargetException wraps an exception thrown by the method invoked
  830.      * @throws IllegalAccessException if the requested method is not accessible via reflection
  831.      * @throws NullPointerException if the object or method name are {@code null}
  832.      */
  833.     public static Object invokeMethod(final Object object, final String methodName,
  834.             Object... args) throws NoSuchMethodException,
  835.             IllegalAccessException, InvocationTargetException {
  836.         args = ArrayUtils.nullToEmpty(args);
  837.         return invokeMethod(object, methodName, args, ClassUtils.toClass(args));
  838.     }

  839.     /**
  840.      * Invokes a named method whose parameter type matches the object type.
  841.      *
  842.      * <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
  843.      *
  844.      * <p>This method supports calls to methods taking primitive parameters
  845.      * via passing in wrapping classes. So, for example, a {@link Boolean} object
  846.      * would match a {@code boolean} primitive.</p>
  847.      *
  848.      * @param object invoke method on this object
  849.      * @param methodName get method with this name
  850.      * @param args use these arguments - treat null as empty array
  851.      * @param parameterTypes match these parameters - treat null as empty array
  852.      * @return The value returned by the invoked method
  853.      *
  854.      * @throws NoSuchMethodException if there is no such accessible method
  855.      * @throws InvocationTargetException wraps an exception thrown by the method invoked
  856.      * @throws IllegalAccessException if the requested method is not accessible via reflection
  857.      */
  858.     public static Object invokeMethod(final Object object, final String methodName,
  859.             final Object[] args, final Class<?>[] parameterTypes)
  860.             throws NoSuchMethodException, IllegalAccessException,
  861.             InvocationTargetException {
  862.         return invokeMethod(object, false, methodName, args, parameterTypes);
  863.     }

  864.     /**
  865.      * Invokes a named {@code static} method whose parameter type matches the object type.
  866.      *
  867.      * <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
  868.      *
  869.      * <p>This method supports calls to methods taking primitive parameters
  870.      * via passing in wrapping classes. So, for example, a {@link Boolean} class
  871.      * would match a {@code boolean} primitive.</p>
  872.      *
  873.      * <p>This is a convenient wrapper for
  874.      * {@link #invokeStaticMethod(Class, String, Object[], Class[])}.
  875.      * </p>
  876.      *
  877.      * @param cls invoke static method on this class
  878.      * @param methodName get method with this name
  879.      * @param args use these arguments - treat {@code null} as empty array
  880.      * @return The value returned by the invoked method
  881.      *
  882.      * @throws NoSuchMethodException if there is no such accessible method
  883.      * @throws InvocationTargetException wraps an exception thrown by the
  884.      *  method invoked
  885.      * @throws IllegalAccessException if the requested method is not accessible
  886.      *  via reflection
  887.      */
  888.     public static Object invokeStaticMethod(final Class<?> cls, final String methodName,
  889.             Object... args) throws NoSuchMethodException,
  890.             IllegalAccessException, InvocationTargetException {
  891.         args = ArrayUtils.nullToEmpty(args);
  892.         return invokeStaticMethod(cls, methodName, args, ClassUtils.toClass(args));
  893.     }

  894.     /**
  895.      * Invokes a named {@code static} method whose parameter type matches the object type.
  896.      *
  897.      * <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
  898.      *
  899.      * <p>This method supports calls to methods taking primitive parameters
  900.      * via passing in wrapping classes. So, for example, a {@link Boolean} class
  901.      * would match a {@code boolean} primitive.</p>
  902.      *
  903.      * @param cls invoke static method on this class
  904.      * @param methodName get method with this name
  905.      * @param args use these arguments - treat {@code null} as empty array
  906.      * @param parameterTypes match these parameters - treat {@code null} as empty array
  907.      * @return The value returned by the invoked method
  908.      *
  909.      * @throws NoSuchMethodException if there is no such accessible method
  910.      * @throws InvocationTargetException wraps an exception thrown by the
  911.      *  method invoked
  912.      * @throws IllegalAccessException if the requested method is not accessible
  913.      *  via reflection
  914.      */
  915.     public static Object invokeStaticMethod(final Class<?> cls, final String methodName,
  916.             Object[] args, Class<?>[] parameterTypes)
  917.             throws NoSuchMethodException, IllegalAccessException,
  918.             InvocationTargetException {
  919.         args = ArrayUtils.nullToEmpty(args);
  920.         parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
  921.         final Method method = getMatchingAccessibleMethod(cls, methodName,
  922.                 parameterTypes);
  923.         if (method == null) {
  924.             throw new NoSuchMethodException("No such accessible method: "
  925.                     + methodName + "() on class: " + cls.getName());
  926.         }
  927.         args = toVarArgs(method, args);
  928.         return method.invoke(null, args);
  929.     }

  930.     private static Object[] toVarArgs(final Method method, Object[] args) {
  931.         if (method.isVarArgs()) {
  932.             final Class<?>[] methodParameterTypes = method.getParameterTypes();
  933.             args = getVarArgs(args, methodParameterTypes);
  934.         }
  935.         return args;
  936.     }

  937.     /**
  938.      * {@link MethodUtils} instances should NOT be constructed in standard programming.
  939.      * Instead, the class should be used as
  940.      * {@code MethodUtils.getAccessibleMethod(method)}.
  941.      *
  942.      * <p>This constructor is {@code public} to permit tools that require a JavaBean
  943.      * instance to operate.</p>
  944.      *
  945.      * @deprecated TODO Make private in 4.0.
  946.      */
  947.     @Deprecated
  948.     public MethodUtils() {
  949.         // empty
  950.     }
  951. }