在Java中将接口类作为参数传递

ale*_*erc 34 java interface

我有一个界面:

public interface IMech {

}
Run Code Online (Sandbox Code Playgroud)

以及实现它的类

public class Email implements IMech {

}
Run Code Online (Sandbox Code Playgroud)

以及实现此方法的第三个类:

public void sendNotification( Class< IMech > mechanism ){
}
Run Code Online (Sandbox Code Playgroud)

现在我试图像这样调用这种方法

foo.sendNotification(Email.class);
Run Code Online (Sandbox Code Playgroud)

但我一直有例外说:

The method sendNotification(Class<IMech>) in the type RemediationOperator is not applicable for the arguments (Class<Email>)
Run Code Online (Sandbox Code Playgroud)

如果它接口那个类,这不应该工作吗?

axt*_*avt 49

也许你需要

public void sendNotification( Class<? extends IMech> mechanism ) { 
Run Code Online (Sandbox Code Playgroud)


Mik*_*els 10

由于两个类Class<IMechanism>Class<EmailNotification>本身通过的传承关系,即使IMechanismEmailNotification .

你需要让你的方法接受一个Class<? extends IMechanism>.


小智 5

您的参数机制需要使用有界通配符,如下所示:

public void sendNotification(Class <?extends IMech> mechanism){}

引用泛型教程链接文本

通常,如果Foo是Bar的子类型(子类或子接口),并且G是某种泛型类型声明,则不是G是G的子类型的情况.