Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Interface Class as a Parameter in Java

Tags:

java

interface

I have an interface:

public interface IMech {  } 

and a class that implements it

public class Email implements IMech {  } 

and a third class that has this method implemented:

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

now I'm trying to call that method like so

foo.sendNotification(Email.class); 

but i keep getting an exception saying:

The method sendNotification(Class<IMech>) in the type RemediationOperator is not applicable for the arguments (Class<Email>) 

Shouldn't this work if it interfaces that class?

like image 825
aleclerc Avatar asked May 18 '10 17:05

aleclerc


People also ask

Can an interface be passed as a parameter?

Yes, you can pass Interface as a parameter in the function.

Can interface methods have parameters Java?

A Java interface is a bit like a Java class, except a Java interface can only contain method signatures and fields. A Java interface is not intended to contain implementations of the methods, only the signature (name, parameters and exceptions) of the method.

Can we pass interface in constructor?

It is perfectly acceptable to declare an argument to a constructor or method that is an interface type. In fact that is a good practice.


1 Answers

Perhaps you need

public void sendNotification( Class<? extends IMech> mechanism ) {  
like image 58
axtavt Avatar answered Oct 08 '22 17:10

axtavt