java 反射工具包reflections
阿新 • • 發佈:2017-12-04
分享圖片 class ref logs annotate .get pan can sys
reflections 中包含很多的Scanner ,也就是掃描器,調用對應的方法時需要有配置對應的掃描器,不然程序會拋出異常.
掃描器結構:
使用時,我們主要使用Reflections 這個類來調用.
Reflections 默認配置了一部分掃描器,
但是在實際使用時需要添加很多的掃描器,可以根據程序拋出的異常進行添加對應的掃描
使用方法:
Reflections reflections = new Reflections("cn.*", new MethodAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner(), newMethodParameterNamesScanner());
指明掃描的包路徑,並配置掃描器
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
java 反射工具包reflections