1

In this question, I saw that I can use a helper method to 'capture' the wildcard generic into a type T to do type safe operations, like so:

void foo(List<?> i) {
    fooHelper(i);
}

private <T> void fooHelper(List<T> l) {
    l.set(0, l.get(0));
}

But when I try to do that with the extends keyword, it doesn't work:

void bar() {
    barHelper(String.class); //works fine
}

void bar(Class<? extends Comparable<?>> clazz) {
    barHelper(clazz); //doesn't compile
}

<T> void barHelper(Class<? extends Comparable<T>> clazz) { }

I get the following error:

The method fooHelper
    (Class<? extends Comparable<T>>)
in the type Test is not applicable for the arguments
    (Class<capture#1-of ? extends Comparable<?>>)

Is there a way to capture a wildcard when using the extends keyword?

My background is, I have a list of classes that extends a given class A, each one of them with a different generic argument T. For each class, I want to get a reference to its T class, and I was trying to do it type safely.

Community
  • 1
  • 1
Luan Nico
  • 5,376
  • 2
  • 30
  • 60

1 Answers1

3

I think generic constraints must be where the type parameter <T> is declared, so instead of

<T> void barHelper(Class<? extends Comparable<T>> clazz) { }

I would write

<A, B extends A> void barHelper(Class<B> clazz) { }

Or if the super/top class is known

<T extends MySuperType> void barHelper(Class<T> clazz) { }
cchantep
  • 9,118
  • 3
  • 30
  • 41