查找方法
//package com.nowjava; /*来自 时代Java公众号 - N o w J a v a . c o m*/ import java.lang.reflect.Method; import java.util.Arrays; public class Main { public static Method findMethod(Class<?> beanClass, boolean allowNonPublic, String name, Class<?>[] argumentTypes) { Method[] candidates = allowNonPublic ? beanClass.getDeclaredMethods() : beanClass.getMethods(); sortMethods(candidates); for (Method candidate : candidates) { if (candidate.getName().equals(name) && matchParameterTypes(candidate.getParameterTypes(), argumentTypes)) { return candidate; } } return null; } private static <T> void sortMethods(Method[] methods) { Arrays.sort(methods, (method1, method2) -> compareParameterTypes(method1.getParameterTypes(), method2.getParameterTypes()));/** 来自 nowjava.com**/ } private static boolean matchParameterTypes(Class<?>[] parameterTypes, Class<?>[] argumentTypes) { if (parameterTypes.length == argumentTypes.length) { boolean match = true; for (int i = 0; i < parameterTypes.length; i++) { if (!parameterTypes[i].isAssignableFrom(argumentTypes[i])) { match = false; break; } } return match; } else { return false; } } private static int compareParameterTypes(Class<?>[] parameterTypes1, Class<?>[] parameterTypes2) { if (parameterTypes1.length != parameterTypes2.length) { return 0; } else { int result = 0; for (int i = 0; result == 0 && i < parameterTypes1.length; i++) { Class<?> parameterType1 = parameterTypes1[i];