一、使用reflections
@Service
public class TFactory {
@PostConstruct
public void init() throws IllegalAccessException, InstantiationException {
Reflections reflections = new Reflections("com.test");
Set<Class<? extends ISuperClass>> classSet = reflections.getSubTypesOf(ISuperClass.class);
for (Class<? extends ISuperClass> clazz : classSet){
ISuperClass obj = clazz.newInstance();
}
}
}
<!-- 需要引入的jar包 -->
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.10</version>
</dependency>
二、使用Srping框架提供的ClassPathScanningCandidateComponentProvider
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(MyClass.class));
Set components = provider.findCandidateComponents("com.test");
for (BeanDefinition component : components) {
Class cls = Class.forName(component.getBeanClassName());
}