反射框架Reflections

网友投稿 677 2022-11-14

反射框架Reflections

反射框架Reflections

​​Github (opens new window)​​

​​#​​ 一、简介

Reflections通过扫描classpath,索引元数据,并且允许在运行时查询这些元数据。

使用Reflections可以很轻松的获取以下元数据信息:

获取某个类型的全部子类只要类型、构造器、方法,字段上带有特定注解,便能获取带有这个注解的全部信息(类型、构造器、方法,字段)获取所有能匹配某个正则表达式的资源获取所有带有特定签名的方法,包括参数,参数注解,返回类型获取所有方法的名字获取代码里所有字段、方法名、构造器的使用权

​​#​​ 二、Maven依赖

org.reflections reflections 0.9.11

1 2 3 4 5

​​#​​ 三、使用方法

​​#​​ 3.1 实例化

指定要扫描的包名

// 实例化Reflections,并指定要扫描的包名Reflections reflections = new Reflections("my.project");// 获取某个类的所有子类Set> subTypes = reflections.getSubTypesOf(SomeType.class);// 获取包含某个注解的所有类Set> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class);

1 2 3 4 5 6 7

指定要扫描的包名并添加过滤器

​​ConfigurationBuilder API (opens new window)​​

Reflections reflections = new Reflections( new ConfigurationBuilder() .forPackage("com.my.project") .filterInputsBy(new FilterBuilder().includePackage("com.my.project")));

1 2 3 4

添加扫描器

​​Scanners API (opens new window)​​

// scan package with specific scannersReflections reflections = new Reflections( new ConfigurationBuilder() .forPackage("com.my.project") .filterInputsBy(new FilterBuilder().includePackage("com.my.project").excludePackage("com.my.project.exclude")) .setScanners(TypesAnnotated, MethodsAnnotated, MethodsReturn));// scan package with all standard scannersReflections reflections = new Reflections("com.my.project", Scanners.values());

1 2 3 4 5 6 7 8 9

​​#​​ 3.2 扫描子类

Set> modules = reflections.getSubTypesOf(com.google.inject.Module.class);

1 2

​​#​​ 3.3 扫描注解

//TypeAnnotationsScanner Set> singletons = reflections.getTypesAnnotatedWith(javax.inject.Singleton.class);

1 2 3

​​#​​ 3.4 扫描资源

//ResourcesScannerSet properties = reflections.getResources(Pattern.compile(".*\\.properties"));

1 2 3

​​#​​ 3.5 扫描方法、构造注解

//MethodAnnotationsScannerSet resources = reflections.getMethodsAnnotatedWith(javax.ws.rs.Path.class);Set injectables = reflections.getConstructorsAnnotatedWith(javax.inject.Inject.class);

1 2 3 4 5

​​#​​ 3.6 扫描字段注解

Set ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);

1 2

​​#​​ 3.7 扫描方法参数

//MethodParameterScannerSet someMethods = reflections.getMethodsMatchParams(long.class, int.class);Set voidMethods = reflections.getMethodsReturn(void.class);Set pathParamMethods = reflections.getMethodsWithAnyParamAnnotated(PathParam.class);

1 2 3 4 5 6 7

​​#​​ 3.8 扫描方法参数名

List parameterNames = reflections.getMethodParamNames(Method.class)

1 2

​​#​​ 3.9 扫描方法调用情况

//MemberUsageScannerSet usages = reflections.getMethodUsages(Method.class)

1 2 3

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:年终总结汇报大纲
下一篇:SpringMVC中重定向model值的获取方式
相关文章

 发表评论

暂时没有评论,来抢沙发吧~