1. 程式人生 > 程式設計 >Java反射框架Reflections示例詳解

Java反射框架Reflections示例詳解

MAVEN 座標

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

Reflections 的作用

Reflections通過掃描classpath,索引元資料,並且允許在執行時查詢這些元資料。

  • 獲取某個型別的所有子類;比如,有一個父類是TestInterface,可以獲取到TestInterface的所有子類。
  • 獲取某個註解的所有型別/欄位變數,支援註解引數匹配。
  • 使用正則表示式獲取所有匹配的資原始檔
  • 獲取特定簽名方法。

使用Reflections可以很輕鬆的獲取以下元資料資訊:

專案中使用:

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

到此這篇關於Java反射框架Reflections示例詳解的文章就介紹到這了,更多相關Java反射框架Reflections內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!