简体   繁体   English

如何使用课堂 <Interface> Java中的方法签名

[英]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中, 即使BA继承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.

相关问题 接口和类中的方法签名相同 - same method signature in interface and class 如何使用MethodHandles在实现Java 8接口的类上调用方法? - How to use MethodHandles to call a method on the class that implements an interface in Java 8? 如何在Java 8编译时确保方法签名“实现”功能接口 - How to ensure at Java 8 compile time that a method signature “implements” a functional interface Java Class 不能覆盖抽象 class 中的方法,该方法签名包含一个接口 - Java Class cannot override method in abstract class which has a method signature that contains an interface 通过功能接口方法签名获取 class 构造函数 - Get class constructor by functional interface method signature 给定方法签名,如何获取方法所属的java类? - How to get the java Class to which a method belongs given the method signature? Java Collection接口addAll()方法签名 - Java Collection Interface addAll() method signature 解释 Java 8 收集器接口/方法签名 - Explaining Java 8 Collector Interface/Method Signature 如何在java中的多个类中使用一个接口? - How to use one interface in multiple class in java? 如何减少子 class 中方法签名中的变量数量? Java 重构 - How to reduce the number of variables in the signature of method in child class? Java refactoring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM