我有一个ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();
。当我尝试迭代它时,我得到:
Incopatible types:
Required: java.lang.Class <? extends IMyInterface>
Found: IMyInterface
我的迭代
for (IMyInterface iMyInterface : IMyInterface.getMyPluggables()) {}
红色代码警告突出显示(Android Studio)
Error:(35, 90) error: incompatible types: Class<? extends IMyInterface> cannot be converted to IMyInterface
我愿意
ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();
for (Class<? extends IMyInterface> myClass : classes) {
if (myClass instanceof IMyInterface) {
View revPluggableViewLL = myClass.getMyInterfaceMethod();
}
}
错误
Inconvertible types; cannot cast 'java.lang.Class<capture<? extends com.myapp.IMyInterface>>' to 'com.myapp.IMyInterface'
我怎样才能迭代它?
提前谢谢大家。
最佳答案
您想要迭代 IMyInterface
的实例,因为您想要调用 IMyInterface
的特定方法:
View revPluggableViewLL = myClass.getMyInterfaceMethod();
问题是您声明了 Class
实例的 List
:
ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();
它不包含任何 IMyInterface
实例,而仅包含 Class
实例。
为了满足您的需求,请声明 IMyInterface
列表:
List<IMyInterface> instances = new ArrayList<>();
并以这种方式使用它:
for (IMyInterface myInterface : instances ) {
View revPluggableViewLL = myInterface.getMyInterfaceMethod();
}
请注意,不需要进行此检查:
if (myClass instanceof IMyInterface) {
View revPluggableViewLL = myClass.getMyInterfaceMethod();
}
您操作 IMyInterface
的 List
,因此 List
的元素必然是 IMyInterface
的实例。
关于java - 如何迭代 ArrayList<Class<?扩展接口(interface)>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47069784/