【问题标题】:How to add a class implementing an interface to an ArrayList如何将实现接口的类添加到 ArrayList
【发布时间】:2017-11-02 04:59:04
【问题描述】:

为了避免在接口中实现所有方法,我创建了一个实现接口的抽象类,然后让其他类扩展抽象类并仅覆盖所需的方法。

我正在为我的应用构建 API/框架。

我想将作为接口 IMyInterface 接口实例的类添加到ArrayList

ArrayList<Class<IMyInterface>> classes = new ArrayList<>();  
classes.add(MyClass.class);  

这里是我的班级

class MyClass extends AbstractIMyInterface {}  

这里是AbstractIMyInterface

class AbstractIMyInterface implements IMyInterface {}  

到目前为止,这似乎是不可能的。我上面的方法不起作用:

add (java.lang.Class<com.app.IMyInterface>)
in ArrayList cannot be applied to
(java.lang.Class<com.myapp.plugin.plugin_a.MyClass>)

我怎样才能使这项工作,即:添加一个类扩展另一个类到 ArrayList

【问题讨论】:

  • 看起来你试图添加一个不是IMyInterface对象的类的对象
  • 感谢您的回复。 @Prashant 的正确方法是什么?

标签: java android arraylist polymorphism


【解决方案1】:

您需要使用通配符? extends IMyInterface

ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();

ArrayList&lt;Class&lt;IMyInterface&gt;&gt; classes中,只能添加Class&lt;IMyInterface&gt;

【讨论】:

  • 我刚刚接受了你的回答@ramanlfc。然而,我正在努力迭代ArrayList&lt;Class&lt;? extends IMyInterface&gt;&gt; classes = new ArrayList&lt;&gt;();。如果您能提供帮助,我发布了一个后续问题 How to interate a ArrayList<Class<? extends IMyInterface>>。感谢您迄今为止的帮助。
【解决方案2】:

您可以为此使用?

List<Class <? extends IMyInterface>> arrayList = new ArrayList<>();

【讨论】:

    【解决方案3】:

    我可以这样添加,希望对你有帮助

     public class MyClass extends AbstractIMyInterface {
        @Override
        public void onEating() {
            //from interface
        }
    
        @Override
        void onRunning() {
            //from abstract
        }
    
        public static void main(String[] args){
    
            ArrayList<IMyInterface> iMyInterfaces = new ArrayList<>();
            MyClass myClass = new MyClass();
            iMyInterfaces.add(myClass);
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 2021-09-01
      相关资源
      最近更新 更多