【问题标题】:How to reference the generic type of a member of an inner class?如何引用内部类成员的泛型类型?
【发布时间】:2021-06-12 00:33:27
【问题描述】:

我很想知道为什么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;
}

testStaticInnerClasstestOtherClass 可以正常工作,但我不确定为什么 testInnerClass 会失败。

【问题讨论】:

    标签: java generics nested inner-classes type-erasure


    【解决方案1】:

    InnerClassTest 的内部类,它需要泛型参数。 所以你需要将类声明更新为:

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

    StaticInnerClass,即使在Test 内部,它也被声明为static。所以就像每个static 方法或变量一样,static 类也不依赖于类的任何状态。因此不需要S extends Test&lt;I,S,O&gt;.StaticInnerClass

    【讨论】:

    • 基于 OP 最近更新的新解决方案将是 Test&lt;I extends Test&lt;I,S,O&gt;.InnerClass, ...&gt;。无论如何,有关该问题的更多信息:What is a raw type and why shouldn't we use it?
    • 啊哈!感谢 Gautham 的简洁明了的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多