Java 反射Reflections应用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java 反射Reflections应用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2103字,纯文字阅读大概需要4分钟。
内容图文
![Java 反射Reflections应用](/upload/InfoBanner/zyjiaocheng/635/0dac59433268484a8f60bdb546a0ce15.jpg)
转载https://www.cnblogs.com/boothsun/p/11146827.html
本文只为自己学习做记录
一、Maven 坐标
<dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.10</version> </dependency>
二、Reflections作用
Reflections通过扫描classpath,索引元数据,并且允许在运行时查询这些元数据。
使用Reflections可以很轻松的获取以下元数据信息:
- 获取某个类型的所有子类;比如,有一个父类是TestInterface,可以获取到TestInterface的所有子类。
- 获取某个注解的所有类型/字段变量,支持注解参数匹配。
- 使用正则表达式获取所有匹配的资源文件
- 获取特定签名方法。
三、Demo
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); } }
内容总结
以上是互联网集市为您收集整理的Java 反射Reflections应用全部内容,希望文章能够帮你解决Java 反射Reflections应用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。