Java 運行時元數據分析:Reflections
Reflections 通過掃描 classpath,索引元數據,允許在運行時查詢這些元數據,也可以保存收集項目中多個模塊的元數據信息。
使用 Reflections 可以查詢以下元數據信息:
1)獲得某個類型的所有子類型
2)獲得標記了某個注解的所有類型/成員變量,支持注解參數匹配。
3)使用正則表達式獲得所有匹配的資源文件
4)獲得所有特定簽名(包括參數,參數注解,返回值)的方法
Reflections 依賴 Google 的 Guava 庫和 Javassist 庫。
Maven 項目導入
<dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.10</version> </dependency>
通常用法:
Reflections reflections = new Reflections("my.project"); Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class);
Reflections 初始化代碼。
//scan urls that contain 'my.package', include inputs starting with 'my.package', use the default scanners Reflections reflections = new Reflections("my.package"); //or using ConfigurationBuilder new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("my.project.prefix")) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner().filterResultsBy(optionalFilter), ...), .filterInputsBy(new FilterBuilder().includePackage("my.project.prefix")) ...);
以下是一些使用例子代碼。
//SubTypesScanner Set<Class<? extends Module>> modules = reflections.getSubTypesOf(com.google.inject.Module.class);
//TypeAnnotationsScanner Set<Class<?>> singletons = reflections.getTypesAnnotatedWith(javax.inject.Singleton.class);
//ResourcesScanner Set<String> properties = reflections.getResources(Pattern.compile(".*\\.properties"));
//MethodAnnotationsScanner Set<Method> resources = reflections.getMethodsAnnotatedWith(javax.ws.rs.Path.class); Set<Constructor> injectables = reflections.getConstructorsAnnotatedWith(javax.inject.Inject.class);
//FieldAnnotationsScanner Set<Field> ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);
//MethodParameterScanner Set<Method> someMethods = reflections.getMethodsMatchParams(long.class, int.class); Set<Method> voidMethods = reflections.getMethodsReturn(void.class); Set<Method> pathParamMethods = reflections.getMethodsWithAnyParamAnnotated(PathParam.class);
//MethodParameterNamesScanner List<String> parameterNames = reflections.getMethodParamNames(Method.class)
//MemberUsageScanner Set<Member> usages = reflections.getMethodUsages(Method.class)
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!