Java – How to add a class that implements an interface to an ArrayList

How to add a class that implements an interface to an ArrayList… here is a solution to the problem.

How to add a class that implements an interface to an ArrayList

To solve the problem of having to implement all methods in an interface, I create an abstract class that implements the interface, and then have other classes extend that abstract class and overwrite only the required methods.

I’m building an API/framework for my app.

I want to add IMyInterface as an instance of the interface to 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 method above doesn’t work :

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

How can I do this, i.e.: add a class that extends another class to the ArrayList

Solution

You need to use the wildcard character ? extends IMyInterface

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

In ArrayList<Class<IMyInterface

>> classes, you can only add Classes<IMyInterface>

Related Problems and Solutions