Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

I am building an API / Framework for my app.

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

Here is MyClass

class MyClass extends AbstractIMyInterface {}  

Here is 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>)

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

like image 980
Program-Me-Rev Avatar asked Jan 30 '23 07:01

Program-Me-Rev


2 Answers

you need to use wildcard ? extends IMyInterface.

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

In ArrayList<Class<IMyInterface>> classes , you can only add Class<IMyInterface>.

like image 120
Ramanlfc Avatar answered Feb 02 '23 11:02

Ramanlfc


You can use ? for that.

List<Class <? extends IMyInterface>> arrayList = new ArrayList<>();
like image 34
Lakshmikant Deshpande Avatar answered Feb 02 '23 10:02

Lakshmikant Deshpande