Java反射框架Reflections示例详解
MAVEN坐标
org.reflections reflections 0.9.10
Reflections的作用
Reflections通过扫描classpath,索引元数据,并且允许在运行时查询这些元数据。
- 获取某个类型的所有子类;比如,有一个父类是TestInterface,可以获取到TestInterface的所有子类。
- 获取某个注解的所有类型/字段变量,支持注解参数匹配。
- 使用正则表达式获取所有匹配的资源文件
- 获取特定签名方法。
使用Reflections可以很轻松的获取以下元数据信息:
项目中使用:
publicclassReflectionTest{ publicstaticvoidmain(String[]args){ //扫包 Reflectionsreflections=newReflections(newConfigurationBuilder() .forPackages("com.boothsun.reflections")//指定路径URL .addScanners(newSubTypesScanner())//添加子类扫描工具 .addScanners(newFieldAnnotationsScanner())//添加属性注解扫描工具 .addScanners(newMethodAnnotationsScanner())//添加方法注解扫描工具 .addScanners(newMethodParameterScanner())//添加方法参数扫描工具 ); //反射出子类 Set>set=reflections.getSubTypesOf(ISayHello.class); System.out.println("getSubTypesOf:"+set); //反射出带有指定注解的类 Set >ss=reflections.getTypesAnnotatedWith(MyAnnotation.class); System.out.println("getTypesAnnotatedWith:"+ss); //获取带有特定注解对应的方法 Set methods=reflections.getMethodsAnnotatedWith(MyMethodAnnotation.class); System.out.println("getMethodsAnnotatedWith:"+methods); //获取带有特定注解对应的字段 Set fields=reflections.getFieldsAnnotatedWith(Autowired.class); System.out.println("getFieldsAnnotatedWith:"+fields); //获取特定参数对应的方法 Set someMethods=reflections.getMethodsMatchParams(long.class,int.class); System.out.println("getMethodsMatchParams:"+someMethods); Set voidMethods=reflections.getMethodsReturn(void.class); System.out.println("getMethodsReturn:"+voidMethods); Set pathParamMethods=reflections.getMethodsWithAnyParamAnnotated(PathParam.class); System.out.println("getMethodsWithAnyParamAnnotated:"+pathParamMethods); } }
具体也可以参见官方文档:官方API
到此这篇关于Java反射框架Reflections示例详解的文章就介绍到这了,更多相关Java反射框架Reflections内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。