问题描述
我有一个 ArrayList< Class<?扩展IMyInterface>> classes = new ArrayList<>();
。当我尝试迭代它时,我得到:
I have an ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();
. When I try to iterate it, I get:
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();
}
}
ERROR
Inconvertible types; cannot cast 'java.lang.Class<capture<? extends com.myapp.IMyInterface>>' to 'com.myapp.IMyInterface'
我该怎么办?重复一遍呢?
How can I go about iterating through it?
提前谢谢大家。
推荐答案
您想要根据需要迭代 IMyInterface
的实例调用的特定方法IMyInterface
:
You want to iterate on instances of IMyInterface
as you want to invoke a specific method of IMyInterface
:
View revPluggableViewLL = myClass.getMyInterfaceMethod();
问题是您声明了列表
Class
实例:
The problem is that you declared a List
of Class
instances :
ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();
它不包含任何 IMyInterface的实例
但只有 Class
个实例。
It doesn't contain any instance of IMyInterface
but only Class
instances.
为了满足您的需要,请声明一个列表IMyInterface
:
To achieve your need, declare a list of IMyInterface
:
List<IMyInterface> instances = new ArrayList<>();
以这种方式使用它:
for (IMyInterface myInterface : instances ) {
View revPluggableViewLL = myInterface.getMyInterfaceMethod();
}
请注意,此检查不是必需的:
Note that this check is not required :
if (myClass instanceof IMyInterface) {
View revPluggableViewLL = myClass.getMyInterfaceMethod();
}
您操纵列表
IMyInterface
,因此 List
的元素必然是 IMyInterface的实例
。
You manipulate a List
of IMyInterface
, so elements of the List
are necessarily instances of IMyInterface
.
这篇关于如何交互ArrayList< Class<?扩展IMyInterface>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!