java 反射工具包reflections


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




 


免責聲明!

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



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