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 scannersReflections reflections = new Reflections("my.package");//or using ConfigurationBuildernew Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("my.project.prefix")) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner().filterResultsBy(optionalFilter), ...), .filterInputsBy(new FilterBuilder().includePackage("my.project.prefix")) ...);以下是一些使用例子代码。
//SubTypesScannerSet<Class<? extends Module>> modules = reflections.getSubTypesOf(com.google.inject.Module.class);//TypeAnnotationsScanner Set<Class<?>> singletons = reflections.getTypesAnnotatedWith(javax.inject.Singleton.class);//ResourcesScannerSet<String> properties = reflections.getResources(Pattern.compile(".*\\.properties"));//MethodAnnotationsScannerSet<Method> resources = reflections.getMethodsAnnotatedWith(javax.ws.rs.Path.class);Set<Constructor> injectables = reflections.getConstructorsAnnotatedWith(javax.inject.Inject.class);//FieldAnnotationsScannerSet<Field> ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);//MethodParameterScannerSet<Method> someMethods = reflections.getMethodsMatchParams(long.class, int.class);Set<Method> voidMethods = reflections.getMethodsReturn(void.class);Set<Method> pathParamMethods = reflections.getMethodsWithAnyParamAnnotated(PathParam.class);//MethodParameterNamesScannerList<String> parameterNames = reflections.getMethodParamNames(Method.class)//MemberUsageScannerSet<Member> usages = reflections.getMethodUsages(Method.class)
评论