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

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

这篇关于如何将实现接口的类添加到 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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