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

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

我正在为我的应用程序构建API / Framework.

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

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

这是MyClass

class MyClass extends AbstractIMyInterface {}

这是AbstractIMyInterface

class AbstractIMyInterface implements IMyInterface {}

到目前为止这似乎不可能.我上面的方法不起作用:

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

我该如何工作,即:添加一个将另一个类扩展到ArrayList的类

解决方法

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

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

在ArrayList< Class< IMyInterface>>类,你只能添加Class< IMyInterface>.

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...