Peter Mel
Peter Mel

Reputation: 367

How to pass a Class object with generics of a base interface?

So I have the following method:

void doSomething(Class<MyInterface> klass) { }

Great! Now I do:

class MyClass implements MyInterface { }

// now let's call the method
doSomething(MyClass.class); // DOES NOT COMPILE

Why ??? How do I solve this without adding generics to the class that has the method doSomething?

Upvotes: 2

Views: 399

Answers (2)

rdalmeida
rdalmeida

Reputation: 1853

You can also do:

<K extends MyInterface> void doSomething(Class<K> klass) { }

Then you can use the generic K inside the method, if needed.

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213391

Why ???

Because generics are not covariant. Even though MyInterface is super type of MyClass, Class<MyInterface> is not super type of Class<MyClass>.

How do I solve this without adding generics to the class that has the method doSomething?

Change your method definition to:

void doSomething(Class<? extends MyInterface> klass) { }

Upvotes: 5

Related Questions