问题
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
回答1:
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>
.
回答2:
You can use ?
for that.
List<Class <? extends IMyInterface>> arrayList = new ArrayList<>();
回答3:
I am able to add this way, hope this is helpful
public class MyClass extends AbstractIMyInterface {
@Override
public void onEating() {
//from interface
}
@Override
void onRunning() {
//from abstract
}
public static void main(String[] args){
ArrayList<IMyInterface> iMyInterfaces = new ArrayList<>();
MyClass myClass = new MyClass();
iMyInterfaces.add(myClass);
}
}
来源:https://stackoverflow.com/questions/47067888/how-to-add-a-class-implementing-an-interface-to-an-arraylist