Java非常好用的反射框架Reflections


MAVEN 坐標

<dependency>
  <groupId>org.reflections</groupId>
  <artifactId>reflections</artifactId>
  <version>0.9.10</version>
</dependency>

Reflections 的作用

Reflections通過掃描classpath,索引元數據,並且允許在運行時查詢這些元數據。

使用Reflections可以很輕松的獲取以下元數據信息:

  • 獲取某個類型的所有子類;比如,有一個父類是TestInterface,可以獲取到TestInterface的所有子類。
  • 獲取某個注解的所有類型/字段變量,支持注解參數匹配。
  • 使用正則表達式獲取所有匹配的資源文件
  • 獲取特定簽名方法。

項目中使用:

public class ReflectionTest {
    public static void main(String[] args) {
        // 掃包
        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .forPackages("com.boothsun.reflections") // 指定路徑URL
                .addScanners(new SubTypesScanner()) // 添加子類掃描工具
                .addScanners(new FieldAnnotationsScanner()) // 添加 屬性注解掃描工具
                .addScanners(new MethodAnnotationsScanner() ) // 添加 方法注解掃描工具
                .addScanners(new MethodParameterScanner() ) // 添加方法參數掃描工具
                );

        // 反射出子類
        Set<Class<? extends ISayHello>> set = reflections.getSubTypesOf( ISayHello.class ) ;
        System.out.println("getSubTypesOf:" + set);

        // 反射出帶有指定注解的類
        Set<Class<?>> ss = reflections.getTypesAnnotatedWith( MyAnnotation.class );
        System.out.println("getTypesAnnotatedWith:" + ss);

        // 獲取帶有特定注解對應的方法
        Set<Method> methods = reflections.getMethodsAnnotatedWith( MyMethodAnnotation.class ) ;
        System.out.println("getMethodsAnnotatedWith:" + methods);

        // 獲取帶有特定注解對應的字段
        Set<Field> fields = reflections.getFieldsAnnotatedWith( Autowired.class ) ;
        System.out.println("getFieldsAnnotatedWith:" + fields);

        // 獲取特定參數對應的方法
        Set<Method> someMethods = reflections.getMethodsMatchParams(long.class, int.class);
        System.out.println("getMethodsMatchParams:" + someMethods);

        Set<Method> voidMethods = reflections.getMethodsReturn(void.class);
        System.out.println( "getMethodsReturn:" + voidMethods);

        Set<Method> pathParamMethods =reflections.getMethodsWithAnyParamAnnotated( PathParam.class);
        System.out.println("getMethodsWithAnyParamAnnotated:" + pathParamMethods);
    }
}

具體也可以參見官方文檔:官方API


免責聲明!

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



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