sydnal
sydnal

Reputation: 317

Java generics, a way to enforce either super or subtype

Assume I have a class and a method such as this:

class MyClass<T> {

    void doStuff(Wrapper<T> wrapper) {
        //impl.
    }
}

Generic bounds of the parameter "wrapper" can be modified to Wrapper<? extends T> to make the method accept subtypes of T, and Wrapper<? super T> to accept super types. However, is there a way to modify MyClass such that it accepts both sub and super types of T (not any type), and there is only one method name? (there can be overloads)

I could simply go with Wrapper<?> of course, but "accept anything" is not the same as "accept something that's in the class hierarchy for T". I could also make 2 separate methods, one with <? super T> and one with <? extends T>, but then these methods would need different names, since the signature is the same after erasure.

Note: Please consider this a question out of curiosity.

Upvotes: 2

Views: 359

Answers (1)

michid
michid

Reputation: 10814

You could try the following

<S extends T> void doStuff(Wrapper<? super S> wrapper)

but would need to double check this satisfies your requirements.

Upvotes: 3

Related Questions