如何将实现接口的类添加到ArrayList [英] How to add a class implementing an interface to an ArrayList

查看:150
本文介绍了如何将实现接口的类添加到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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆