如何将实现接口的类添加到 ArrayList

问题描述:

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

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.

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

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

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

这是MyClass

class MyClass extends AbstractIMyInterface {}  

这里是AbstractIMyInterface

class AbstractIMyInterface implements IMyInterface {}  

到目前为止,这似乎是不可能的.我上面的方法行不通:

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

add (java.lang.Class)
在 ArrayList 中不能应用于
(java.lang.Class)

我怎样才能做到这一点,即:添加一个类,将另一个类扩展到 ArrayList

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

你需要使用通配符 吗?扩展 IMyInterface.

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

ArrayList>中classes ,你只能添加Class.