如何将实现接口的类添加到ArrayList [英] How to add a class implementing an interface to an 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
:
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<com.app.IMyInterface>)
in ArrayList cannot be applied to
(java.lang.Class<com.myapp.plugin.plugin_a.MyClass>)
add (java.lang.Class<com.app.IMyInterface>)
in ArrayList cannot be applied to
(java.lang.Class<com.myapp.plugin.plugin_a.MyClass>)
我该如何进行这项工作,即:添加一个将另一个类扩展到 ArrayList
How can I make this work, ie: Add a class extending another class to an ArrayList
推荐答案
您需要使用通配符? extends IMyInterface
.
ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();
在ArrayList<Class<IMyInterface>> classes
中,您只能添加Class<IMyInterface>
.
这篇关于如何将实现接口的类添加到ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!