spring的反射工具類——org.springframework.util.ReflectionUtils


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM