基於拿來主義,如果在項目中用到與反射相關的操作可直接使用這個類,該類有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;
}
