2

I have a method that should receives a Class<A>, something like:

protected void method(final Class<A> clazz) {
}

Then when I try to call like method(A.class) it do works, but if I try method(B.class), where B is child of A, I get the message "incompatible types".

The solution is change to Class<B>, but I have another childs that I like to pass as argument to this method(), like C.class.

David Rodrigues
  • 12,041
  • 16
  • 62
  • 90
  • 3
    Related: [Is List a subclass of List? Why aren't Java's generics implicitly polymorphic?](http://stackoverflow.com/q/2745265) – Pshemo Apr 20 '17 at 22:05

1 Answers1

8

One solution would be to use a bounded wildcard when defining the parameter:

protected void method(final Class<? extends A> clazz) {
    // Code here...
}

With this, you are allowed to pass A's class directly or any class that extends from A.

Or as Pavlo suggested:

protected <T extends A> void method(final Class<T> clazz) {
    // Code here...
}

Both will work, but it would help to know what you plan to do with clazz so we can select one over the other.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • 4
    I'll suggest using `protected void method(final Class clazz)` will be event better because it allows you to avoid wildcard mess when you will try to call methods on your `clazz`. – Pavlo Viazovskyy Apr 20 '17 at 22:04
  • @PavloViazovskyy what generics mess are you referring to? All you can invoke on a `Class extends A>` are producer methods; and that's simply (e.g.) `A instance = clazz.getInstance();`. – Andy Turner Apr 20 '17 at 22:17
  • @AndyTurner. Yes, you're right. That's my mistake. Since `Class` doesn't have consumer methods (which take `T` as parameter), it's enough to use wildcard version of the method as originally suggested by _Jacob_. – Pavlo Viazovskyy Apr 21 '17 at 15:56