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

Jot*_*ota 5 java generics nested inner-classes type-erasure

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

不兼容的类型:对象无法转换为字符串。

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;
}
Run Code Online (Sandbox Code Playgroud)

testStaticInnerClass并按testOtherClass我的预期工作,但我不确定为什么会testInnerClass失败。

Gau*_*m M 4

InnerClass是一个Test需要通用参数的内部类。因此,您需要将类声明更新为:

class Test<
        I extends Test<I,S,O>.InnerClass,
        S extends Test.StaticInnerClass,
        O extends OtherClass>
Run Code Online (Sandbox Code Playgroud)

StaticInnerClass即使在内部,它Test也是被声明的static。因此,与每个static方法或变量一样,该类static也不依赖于该类的任何状态。因此不需要有S extends Test<I,S,O>.StaticInnerClass

  • 基于 OP 最近更新的新解决方案将是“Test&lt;I extends Test&lt;I,S,O&gt;.InnerClass, ...&gt;”。无论如何,有关该问题的更多信息:[什么是原始类型以及为什么我们不应该使用它?](/sf/ask/193922501/) (2认同)