reflections 中包含很多的Scanner ,也就是掃描器,調用對應的方法時需要有配置對應的掃描器,不然程序會拋出異常.
掃描器結構:
使用時,我們主要使用Reflections 這個類來調用.
Reflections 默認配置了一部分掃描器,
但是在實際使用時需要添加很多的掃描器,可以根據程序拋出的異常進行添加對應的掃描
使用方法:
Reflections reflections = new Reflections("cn.*", new MethodAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner(), new MethodParameterNamesScanner());
指明掃描的包路徑,並配置掃描器
1.獲取所有帶有action注解的類
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Action.class); for (Class<?> action : classes) { RequestMapper request = action.getAnnotation(RequestMapper.class); System.out.println(action + "=RequestMapper==" + request.value()); }
2.獲取所有帶有requestMapper注解的方法
Set<Method> methods = reflections.getMethodsAnnotatedWith(RequestMapper.class); for (Method method : methods) { System.out.println(method.getName() + "=methods==" + reflections.getMethodParamNames(method)); }
獲取某個方法的參數名稱:(jdk里面沒有對應的方法)
reflections.getMethodParamNames
官方文檔:https://github.com/ronmamo/reflections