【问题标题】:How to interate a ArrayList<Class<? extends IMyInterface>>如何迭代 ArrayList<Class<?扩展接口>>
【发布时间】:2018-04-14 15:38:26
【问题描述】:

我有一个ArrayList&lt;Class&lt;? extends IMyInterface&gt;&gt; classes = new ArrayList&lt;&gt;();。当我尝试迭代它时,我得到:

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'  

我该如何迭代它?

提前谢谢大家。

【问题讨论】:

  • 您尝试迭代 ArrayList&lt;Class&lt;? extends IMyInterface&gt;&gt; 而不是 ArrayList&lt;IMyInterface&gt;。顺便说一句,这不是您想要的...Class 是表示该类型的实例,而不是该类型本身的实例。所以instanceof IMyInterface 永远不会是真的。

标签: java arraylist interface iteration


【解决方案1】:

您想在IMyInterface 的实例上进行迭代,因为您想调用IMyInterface 的特定方法:

    View revPluggableViewLL = myClass.getMyInterfaceMethod();

问题是您声明了 ListClass 实例:

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 的实例。

【讨论】:

  • 感谢@davidxxx 的回复。这样,我将无法将IMyInterface 的实例添加到List&lt;IMyInterface&gt; instances = new ArrayList&lt;&gt;();。我需要ArrayList&lt;Class&lt;? extends IMyInterface&gt;&gt; instances = new ArrayList&lt;&gt;();,这样我才能做到instances.add(AClassOfIMyInterface.class);。你有什么建议可以解决它吗?再次感谢您。
  • 不客气。为什么你认为你需要 Classes 在你的 List ? Classes 代表类结构/定义,而不是 IMyInterface 的实例。
  • 这是我之前提出的问题How to add a class implementing an interface to an ArrayList 的后续,我在其中接受了Ramanlfc's answer
  • 我读过。问题是您最初的猜测是错误的。您在这个问题中说:“我想将作为接口 IMyInterface 的实例的类添加到 ArrayList:”但从技术上讲这是不正确的。您的课程根本不是IMyInterface 的实例。您不需要拥有ListClass。你想要的是ListIMyInterface 来操作IMyInterface 的实例。 ListClass 是一个非常具体的要求,通常依赖于反射。你没有提到它,似乎也不需要它。暂时忘掉它吧。
【解决方案2】:

myClassClass 的一个实例,它没有实现IMyInterface(即使它是Class&lt;IMyInterface&gt;)。因此你永远不能在myClass上执行getMyInterfaceMethod()

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 2022-01-14
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多