How to add a class implementing an interface to an ArrayList

我只是一个虾纸丫 提交于 2019-12-13 14:15:49

问题


To go around having to implement ALL the methods in an interface, I created an abstract class that implements an interface, then have other classes extend the abstract class and override only the needed methods.

I am building an API / Framework for my app.

I would like to add classes that are instances of an interface IMyInterface to an ArrayList:

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

Here is MyClass

class MyClass extends AbstractIMyInterface {}  

Here is AbstractIMyInterface

class AbstractIMyInterface implements IMyInterface {}  

So far this seems impossible. My approach above won't work:

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

How can I make this work, ie: Add a class extending another class to an ArrayList


回答1:


you need to use wildcard ? extends IMyInterface.

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

In ArrayList<Class<IMyInterface>> classes , you can only add Class<IMyInterface>.




回答2:


You can use ? for that.

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



回答3:


I am able to add this way, hope this is helpful

 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);

    }
}


来源:https://stackoverflow.com/questions/47067888/how-to-add-a-class-implementing-an-interface-to-an-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!