目录
反射扫描和索引项目的类路径元数据,允许在运行时对类型系统进行反向传递查询。
使用反射,您可以查询元数据,例如:
获取某种类型的所有子类型
获取所有类型/构造函数/方法/字段,并使用一些注释进行注释,可选地使用匹配的注释参数
获取匹配正则表达式的所有资源
获取具有特定签名的所有方法,包括参数、参数注释和返回类型
获取所有方法参数名称
获取代码中的所有字段/方法/构造函数用法
- <dependency>
- <groupId>org.reflectionsgroupId>
- <artifactId>reflectionsartifactId>
- <version>0.10.2version>
- dependency>
- //指定包路径,默认支持Scanners.TypesAnnotated, Scanners.SubTypes 两种扫描类型
- Reflections reflections = new Reflections("com.dora.distribution");
-
- //指定包路径和扫描类型
- Reflections reflections = new Reflections("com.koala.distribution", Scanners.MethodsAnnotated);
-
- //使用Configuration实例化
- Reflections reflections = new Reflections(ConfigurationBuilder.build().forPackage("com.dora.distribution").setScanners(Scanners.values()));
- Reflections reflections = new Reflections("com.dora.distribution");
- //根据父类型查询所有子类型
- Set
extends ApplicationEvent>> bySuperClass = reflections.getSubTypesOf(ApplicationEvent.class);
- Reflections reflections = new Reflections("com.dora.distribution");
- //根据接口查询所有实现类
- Set
extends ApplicationListener>> byInterfaces = reflections.getSubTypesOf(ApplicationListener.class);
- Reflections reflections = new Reflections(ConfigurationBuilder.build().forPackage("com.dora.distribution").setScanners(Scanners.values()));
- //根据注解扫描
- Set
> typesAnnotatedWith = reflections.getTypesAnnotatedWith(RestController.class);
- //指定包路径和扫描类型
- Reflections reflections = new Reflections("com.dora.distribution", Scanners.MethodsAnnotated);
- Set
methodsAnnotatedWith = reflections.getMethodsAnnotatedWith(RequestMapping.class);
- Reflections reflections = new Reflections("com.dora.distribution", Scanners.values());
- Set
byReturnMethods = reflections.getMethodsReturn(String.class);
- Reflections reflections = new Reflections("com.dora.distribution", Scanners.values());
- Set
methodsWithSignature = reflections.getMethodsWithSignature(LoginEvent.class);
- Reflections reflections = new Reflections("com.dora.distribution", Scanners.values());
- Set
resources = reflections.getResources(".*\\.properties");
在Spring 项目中监听SpringEvent只需要在处理方法中增加一个注解 @EventListener 如下:
- @Service
- @Slf4j
- public class PushNotifyService {
-
- @EventListener(LoginEvent.class)
- public void sendPush(LoginEvent loginEvent) {
- log.info("listener 接收到事件是:{}", loginEvent);
- }
- }
在有消息触达的时候就可以使用该方法进行处理,如果我们在自己的项目中也使用类似的设计,就可以使用 Reflections来根据方法的注解来扫描所有方法