Chris Betti
Chris Betti

Reputation: 2923

How do I get a generic type to match if Class<Type> uses ? extends Type?

Given this prototype:

public static <C extends SetComposite, S extends Iterable<U>, U> boolean
eligibleForInclusion(C me, Class<C> clazz, List<S> members) throws TypeCollisionException {
    ...
}

And this call site:

public void include(RestaurantSet member) {
    if (SetCompositeUtils.<RestaurantSetComposite, RestaurantSet, Restaurant>
            eligibleForInclusion(this, this.getClass(), Arrays.asList(member))) {
        inc.add(member);
    }
}

Eclipse compiler gives this error:

The parameterized method <RestaurantSetComposite, RestaurantSet, Restaurant>eligibleForInclusion(RestaurantSetComposite, Class<RestaurantSetComposite>, List<RestaurantSet>) of type SetCompositeUtils is not applicable for the arguments (RestaurantSetComposite, Class<capture#1-of ? extends RestaurantSetComposite>, List<RestaurantSet>)

If I'm reading correctly, Class<capture#1-of ? extends RestaurantSetComposite> is not matching Class<RestaurantSetComposite>. Can I get around this somehow?

Upvotes: 2

Views: 146

Answers (1)

Jeremy
Jeremy

Reputation: 326

Because your this might be an instance of a subclass, this.getClass() might not be exactly RestaurantSetComposite.class, so you need

public static <C extends SetComposite, S extends Iterable<U>, U> boolean
eligibleForInclusion(C me, Class<? extends C> clazz, List<S> members) throws TypeCollisionException {
    ...
}

Upvotes: 2

Related Questions