基于拿来主义,如果在项目中用到与反射相关的操作可直接使用这个类,该类有600多行代码,本人是在阅读springSecurity中的org.springframework.security.authentication.dao.ReflectionSaltSource类时发现该工具类。目前只是读了该类中的一个方法的源码,下面与大家分享:
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
Assert.notNull(clazz, "Class must not be null");
Assert.notNull(name, "Method name must not be null");
Class<?> searchType = clazz;
while (searchType != null) {
//判断当前要反射的类是不是接口,如果是接口则取出接口的方法(包含父接口的方法),
否则则取出类定义的方法(但排除继承的方法)
Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods());
for (Method method : methods) {
//如果方法的名字等于name参数,并且方法的传参为空或与paramTypes相等
if (name.equals(method.getName())
&& (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
return method;
}
}
//如果没找到相应的方法,则对searchType的父类进行同样的查找
searchType = searchType.getSuperclass();
}
return null;
}