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
  • 659
  • 3
  • 13

2 Answers2

3

What about changing the method signature

void doSomething(Class<? extends ICache> cls) {
Reimeus
  • 158,255
  • 15
  • 216
  • 276
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
  • 132,869
  • 46
  • 340
  • 423