Ok, so I have a parametric interface whose implementation has an inner class. It seems I cannot in any way reference the full (generic) type of the inner class, since it is not itself parameterized and only implicity uses the enclosing class’ type parameter:
public interface TestA<R> {
public Class<? extends R> getTheRClass();
}
public class TestB<Z> implements TestA<TestB<Z>.InnerStuff> {
public class InnerStuff {
List<R> iCantBeStatic;
}
InnerStuff myStuff;
@Override
public Class<? extends TestB<Z>.InnerStuff> getTheRClass() {
// return InnerStuff.class;
// return myStuff.getClass();
// return TestB.InnerStuff.class;
// return TestB<Z>.InnerStuff.class;
throw new AngryProgrammerException();
}
}
Is there any way to return the class in question and have the compiler recognize the correct type?? Yes, I know there are 1,001 way to work around the problem (make the inner class static, refactor so there is no inner class, etc, etc) I’d like to know if there is an expression that works in that override, or if no such expression exists…
Due to erasure, the actual
Classinstance that you’re returning will internally just beTestB.InnerStuff.class; the<Z>part doesn’t actually exist at run-time. So your instinct withreturn TestB.InnerStuff.classwas on the money. To get it to work, all you need to do is add a cast to the raw-typeClassto convince the compiler not to squeal:(You can then add an annotation like
@SuppressWarnings({ "unchecked", "rawtypes" })to tell your compiler that you don’t want warning-messages for this.)