2

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. How can I implement this?

Markaos
  • 639
  • 3
  • 13

2 Answers2

3

What about changing the method signature

void doSomething(Class<? extends ICache> cls) {
Reimeus
  • 155,977
  • 14
  • 207
  • 269
2

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. That's why it doesn't compile with SimpleCache.class in your case: Class<SimpleCache> is not a 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. Since SimpleCache respects that bound, it compiles fine.

Community
  • 1
  • 1
Tunaki
  • 125,519
  • 44
  • 317
  • 399