Java 如何交互ArrayList<;类别<;?扩展IMyInterface>&燃气轮机;
我有一个Java 如何交互ArrayList<;类别<;?扩展IMyInterface>&燃气轮机;,java,arraylist,interface,iteration,Java,Arraylist,Interface,Iteration,我有一个ArrayList您想要在IMyInterface的实例上迭代,因为您想要调用IMyInterface的特定方法: View revPluggableViewLL = myClass.getMyInterfaceMethod(); List<IMyInterface> instances = new ArrayList<>(); 问题是您声明了类的列表: ArrayList<Class<? extends IMyInterface>&
ArrayList您想要在IMyInterface
的实例上迭代,因为您想要调用IMyInterface
的特定方法:
View revPluggableViewLL = myClass.getMyInterfaceMethod();
List<IMyInterface> instances = new ArrayList<>();
问题是您声明了类的列表
:
ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();
并以这种方式使用它:
for (IMyInterface myInterface : instances ) {
View revPluggableViewLL = myInterface.getMyInterfaceMethod();
}
请注意,以下情况不需要此检查:
if (myClass instanceof IMyInterface) {
View revPluggableViewLL = myClass.getMyInterfaceMethod();
}
您操作IMyInterface
的列表
,因此列表
的元素必然是IMyInterface
的实例myClass
是类
的实例,它不实现IMyInterface
(即使它是类
)。因此,您永远无法在myClass
上执行getMyInterfaceMethod()
您尝试迭代ArrayList感谢您的响应@davidxxx。这样,我就无法将IMyInterface
的实例添加到List instances=new ArrayList()代码>。我需要arraylisty欢迎你。为什么您认为您需要在列表中Class
es<代码>类
es表示类结构/定义,而不是IMyInterface
的实例。这是我之前提出的一个问题的后续问题,在这个问题中我接受了。我阅读了它。问题是你最初的猜测是错误的。您在这个问题中说:“我想将接口IMyInterface的实例类添加到ArrayList中:”但从技术上讲,这是不正确的。您的类根本不是IMyInterface
的实例。您不需要有类的列表
。您需要的是IMyInterface
的列表
,以操作IMyInterface
的实例<类
的代码>列表
是一个非常具体的要求,通常依赖于反射。你不提它,似乎也不需要它。暂时忘记这一点。
View revPluggableViewLL = myClass.getMyInterfaceMethod();
ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();
List<IMyInterface> instances = new ArrayList<>();
for (IMyInterface myInterface : instances ) {
View revPluggableViewLL = myInterface.getMyInterfaceMethod();
}
if (myClass instanceof IMyInterface) {
View revPluggableViewLL = myClass.getMyInterfaceMethod();
}