Reputation: 367
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
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
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