在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java 运行时元数据分析:Reflections

2017-2-9 13:05| 发布者: zhangjf| 查看: 705| 评论: 0

摘要: Reflections 通过扫描 classpath,索引元数据,允许在运行时查询这些元数据,也可以保存收集项目中多个模块的元数据信息。 使用 Reflections 可以查询以下元数据信息: 1)获得某个类型的所有子类型 2)获得标记 ...
Reflections 通过扫描 classpath,索引元数据,允许在运行时查询这些元数据,也可以保存收集项目中多个模块的元数据信息。


使用 Reflections 可以查询以下元数据信息:
1)获得某个类型的所有子类型
2)获得标记了某个注解的所有类型/成员变量,支持注解参数匹配。
3)使用正则表达式获得所有匹配的资源文件
4)获得所有特定签名(包括参数,参数注解,返回值)的方法

Reflections 依赖 Google 的 Guava 库和 Javassist 库。

Maven 项目导入

  1. <dependency>
  2. <groupId>org.reflections</groupId>
  3. <artifactId>reflections</artifactId>
  4. <version>0.9.10</version>
  5. </dependency>
复制代码

通常用法:

  1. Reflections reflections = new Reflections("my.project");
  2. Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class);
  3. Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class);
复制代码


Reflections 初始化代码。

  1. //scan urls that contain 'my.package', include inputs starting with 'my.package', use the default scanners
  2. Reflections reflections = new Reflections("my.package");
  3. //or using ConfigurationBuilder
  4. new Reflections(new ConfigurationBuilder()
  5. .setUrls(ClasspathHelper.forPackage("my.project.prefix"))
  6. .setScanners(new SubTypesScanner(),
  7. new TypeAnnotationsScanner().filterResultsBy(optionalFilter), ...),
  8. .filterInputsBy(new FilterBuilder().includePackage("my.project.prefix"))
  9. ...);
复制代码

以下是一些使用例子代码。

  1. //SubTypesScanner
  2. Set<Class<? extends Module>> modules =
  3. reflections.getSubTypesOf(com.google.inject.Module.class);
复制代码
  1. //TypeAnnotationsScanner
  2. Set<Class<?>> singletons =
  3. reflections.getTypesAnnotatedWith(javax.inject.Singleton.class);
复制代码
  1. //ResourcesScanner
  2. Set<String> properties =
  3. reflections.getResources(Pattern.compile(".*\.properties"));
复制代码
  1. //MethodAnnotationsScanner
  2. Set<Method> resources =
  3. reflections.getMethodsAnnotatedWith(javax.ws.rs.Path.class);
  4. Set<Constructor> injectables =
  5. reflections.getConstructorsAnnotatedWith(javax.inject.Inject.class);
复制代码
  1. //FieldAnnotationsScanner
  2. Set<Field> ids =
  3. reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);
复制代码
  1. //MethodParameterScanner
  2. Set<Method> someMethods =
  3. reflections.getMethodsMatchParams(long.class, int.class);
  4. Set<Method> voidMethods =
  5. reflections.getMethodsReturn(void.class);
  6. Set<Method> pathParamMethods =
  7. reflections.getMethodsWithAnyParamAnnotated(PathParam.class);
复制代码
  1. //MethodParameterNamesScanner
  2. List<String> parameterNames =
  3. reflections.getMethodParamNames(Method.class)
复制代码
  1. //MemberUsageScanner
  2. Set<Member> usages =
  3. reflections.getMethodUsages(Method.class)
复制代码

项目主页:http://www.open-open.com/lib/view/home/1440247401583


最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-9 20:31

Copyright 2015-2025 djqfx

返回顶部