tags:

views:

88

answers:

1

Having these generic interface and class:

interface TestIntf<T extends TestIntf<T>> 
{
    void test(T param);
}

class TestImpl<T extends TestIntf<T>> implements TestIntf<T> 
{
    @Override
    public void test(T param) { System.out.println(param); }
}

This fails:

Class<? extends TestIntf<?>> clz = TestImpl.class;

(Type mismatch: cannot convert from Class<TestImpl> to Class<? extends TestIntf<?>>)

Why? How to properly provide a reference to TestImpl class to match Class<? extends TestIntf<?>>?

+4  A: 

You can't. Use an unsafe cast.

Class<? extends TestIntf<?>> clz = (Class<? extends TestIntf<?>>) TestImpl.class;

or don't use the inner generics:

Class<? extends TestIntf> clz = TestImpl.class;

Update: When it regards annotations, there is nothing you can do - the annotation has to be changed. You cannot have a class literal represent a generic type.

Bozho
what to do if the class reference is required in annotation? compiler complies on typecast there.
pingw33n
@pingw33n check my update
Bozho
See the API docs for `Object.getClass` (the bolded bit).
Tom Hawtin - tackline