Let's say I have a set of classes as follows:
假设我有一组类:
there is an interface Interface1, and there are two classes Class1 and Class2, both which implement Interface1.
有一个接口Interface1,并且有两个类Class1和Class2,它们都实现了Interface1。
interface Interface1 { }
接口Interface1 { }
class Class1 implements Interface1{ }
类Class1实现Interface1{}
class Class2 implements Interface1{}
类Class2实现Interface1 { }
Now, I want to create a List of classes that implement Interface1. I was trying to do something like:
现在,我想创建一个实现Interface1的类的列表。我想做的是:
List<Class<Interface1>> classes = new List<Class<Interface1>>();
classes.add(Class1.class);
classes.add(Class2.class);
列表 <类
But this doesn't work. I get the compiler error: Class1.class is of type Class<Class1> and so cannot be added to the list
但这是行不通的。我得到了编译器错误:Class1。类是类的类型
Is there a way to achieve what I intend to do?
有没有办法达到我的目的?
1 个解决方案
#1
5
Use a wildcard bounded by your interface
type
使用与您的接口类型绑定的通配符。
List<Class<? extends Interface1>> classes = new ArrayList<Class<? extends Interface1>>();
classes.add(Class1.class);
classes.add(Class2.class);
classes.add(String.class); // won't compile
#1
5
Use a wildcard bounded by your interface
type
使用与您的接口类型绑定的通配符。
List<Class<? extends Interface1>> classes = new ArrayList<Class<? extends Interface1>>();
classes.add(Class1.class);
classes.add(Class2.class);
classes.add(String.class); // won't compile