1.需求
需要扫描某个包中的某个接口的实现类的需求
2.maven 依赖引入
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>
3.扫描org.fhp.test.entity包下的MyInterface的子类
public void testReflections() {
Reflections reflections = new Reflections("org.fhp.test.entity");
Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);
for(Class clazz : classes) {
//logger.info(clazz.getName());
System.out.println("Found: " + clazz.getName());
}
}
4.如果要扫描整个工程的类
假如想扫描整个工程的类,直接new一个不带参数的Reflections就好。值得一提的是,这东西在扫描的时候,连依赖的jar包都不放过。以Spring框架的BeanFactory为例:
public void testReflections() {
Reflections reflections = new Reflections();
Set<Class<? extends BeanFactory>> classes = reflections.getSubTypesOf(BeanFactory.class);
for(Class clazz : classes) {
//logger.info(clazz.getName());
System.out.println("Found: " + clazz.getName());
}
}