How to use Class as a generic type marker

java

Solution

Use an upper-bounded wildcard:

myMethod(Class<? extends MyClass>) {}

You'll probably want to capture the wildcard, too:

<T extends MyClass> void myMethod(Class<T> klass) {}

This time you can refer to `T` in the body.

Problem

I have my method: ``` myMethod(Class class){} ``` I want to pass to this method MyClass with all descending classes, so changed it to: ``` myMethod(Class<MyClass> class){} ``` And call is: ``` myMethod(MyOtherClassExtendingMyClass.class) ``` Then I have compiler error: ``` The method myMethod(Class<MyClass>) in the type XXX is not applicable for the arguments (Class<MyOtherClassExtendingMyClass>) ``` How to get assured that only MyClass with all it's descending classes will be allowed as parameters of this method?

Original source