我有一个项目,其中服务接口使用@Service
注释(自定义注释,而不是 Spring)进行注释,并且每个服务(hibernate、mongodb 等)可以有多个实现。
我正在尝试使用反射加载实现类,如下所示:
第一步:加载所有带@Service
注解的接口
第 2 步:为每个接口加载所有子类
这是代码:
public static void main(String[] args) throws Exception{
Reflections reflections = new Reflections("net.jitix.cfs");
//load annotated interfaces
Set<Class<?>> types=reflections.getTypesAnnotatedWith(Service.class);
Iterator<Class<?>> typeIterator=types.iterator();
typeIterator.forEachRemaining(new Consumer<Class<?>>() {
@Override
public void accept(Class<?> type) {
if(!type.isInterface()){
typeIterator.remove();
}
}
});
for(Class<?> type:types){
//load implementation classes
Set<Class<?>> implTypes=reflections.getSubTypesOf(type); //error here
}
//rest of the code
}
我得到的编译错误:Type mismatch: cannot convert from Set<Class<? extends capture#8-of ?>> to Set<Class<?>>
根据我的理解 Class<?>
,表示类型可以是任何东西,所以我很困惑为什么需要的方法Class<T>
不能Class<?>
作为参数。
谁能帮我理解为什么会这样?我的方法有什么可能的替代方案吗?提前致谢!
编辑:根据@MGorgon 的评论以及@StriplingWarrior 和@Sotirios Delimanolis 使用反射方法的回答是毫无疑问的。有什么方法可以获取引用类型为类型的类型的子类型Class<?>