[英]How to use Class<Interface> in method signature in Java
I am trying to declare a method, which will take any class implementing an interface as its parameter. 我正在尝试声明一个方法,该方法将采用实现接口的任何类作为其参数。 Example:
例:
interface ICache {...}
class SimpleCache implements ICache {...}
void doSomething(Class<ICache> cls) { /* Do something with that class */ }
But when I try to call it with SimpleCache.class
, it doesn't work. 但是,当我尝试使用
SimpleCache.class
调用它时,它不起作用。 How can I implement this? 我该如何实施?
如何更改方法签名
void doSomething(Class<? extends ICache> cls) {
You need to introduce a type parameter: 您需要引入一个类型参数:
<T extends ICache> void doSomething(Class<T> cls) { /* Do something with that class */ }
In Java, a Class<B>
is not a Class<A>
even if B
inherits from A
. 在Java中, 即使
B
从A
继承 , Class<B>
也不是Class<A>
。 That's why it doesn't compile with SimpleCache.class
in your case: Class<SimpleCache>
is not a Class<ICache>
. 这就是为什么它不能与
SimpleCache.class
一起编译的原因: Class<SimpleCache>
不是Class<ICache>
。
Therefore, the solution is to introduce a type T
: we're saying that this method can take any class Class<T>
where T extends ICache
. 因此,解决方案是引入类型
T
:我们说这种方法可以采用T extends ICache
任何类Class<T>
。 Since SimpleCache
respects that bound, it compiles fine. 由于
SimpleCache
遵守该限制,因此可以正常编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.