Luan Nico
Luan Nico

Reputation: 5917

Java Generics capture wildcard with extends

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.

Upvotes: 1

Views: 3259

Answers (1)

cchantep
cchantep

Reputation: 9158

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) { }

Upvotes: 3

Related Questions