如何引用内部class成员的泛型类型?

How to reference the generic type of a member of an inner class?

我很想知道为什么 testInnerClass 编译失败,引用:

incompatible types: Object cannot be converted to String.

import java.util.List;

class Test<
        I extends Test.InnerClass,
        S extends Test.StaticInnerClass,
        O extends OtherClass> {

    void testOtherClass(O other) {
        String firstString = other.strings.get(0); //this works
    }
    
    void testStaticInnerClass(S staticInner) {
        String firstString = staticInner.strings.get(0); //this works
    }
    
    void testInnerClass(I inner) {
        String firstString = inner.strings.get(0); //this fails:
        //"incompatible types: Object cannot be converted to String" 
    }

    static class StaticInnerClass {
        List<String> strings;
    }
    
    class InnerClass {
        List<String> strings;
    }
}

class OtherClass {
    List<String> strings;
}

testStaticInnerClasstestOtherClass 按我的预期工作,但我不确定为什么 testInnerClass 失败。

InnerClassTest 的内部 class,需要通用参数。 因此,您需要将 class 声明更新为:

class Test<
        I extends Test<I,S,O>.InnerClass,
        S extends Test.StaticInnerClass,
        O extends OtherClass>

StaticInnerClass,即使在 Test 中,它被声明为 static。因此,对于每个 static 方法或变量,static class也不依赖于class的任何状态。因此不需要 S extends Test<I,S,O>.StaticInnerClass