【问题标题】:How to reference the nested type of a nested template parameter inside a class?如何在类中引用嵌套模板参数的嵌套类型?
【发布时间】:2016-12-19 06:50:48
【问题描述】:

这是this question 的后续行动。本质上,我有以下课程:

public class Parent<B> {

    public B b;

    public Parent(B b) {
        this.b = b;
    }
}

public class Child<B> extends Parent<B> {

    public Child(B b) {
        super(b);
    }
}

我想要另一个引用它们的类:

public class Foo<ParentType<B> extends Parent<B>, B> {
//                         ^ syntax error here: > expected
    public ParentType<B> parent;
    public B otherItem;

    public Foo(ParentType<B> parent, B otherItem) {
        this.parent = parent;
        this.otherItem = otherItem;
        B b = parent.b;
    }
}

我认为我认为上面应该做什么对人类来说是很清楚的,但 Java 基本上认为它是一个语法混乱,从第一个嵌套的 &lt; 开始。

我尝试删除类模板声明中的&lt;B&gt; 部分:

public class Foo<ParentType extends Parent, B> {
    public ParentType<B> parent;
//         ^ (5:12)
    public B otherItem;

    public Foo(ParentType<B> parent, B otherItem) {
//                     ^ same error here
        this.parent = parent;
        this.otherItem = otherItem;
        B b = parent.b;
    }
}

但 IntelliJ 抱怨

类型'ParentType'没有类型参数

编译器报错:

Error:(5, 12) java: unexpected type
  required: class
  found:    type parameter ParentType

如果我让代码看起来像这样,最终我可以消除所有错误:

public class Foo<ParentType extends Parent, B> {
    public ParentType parent;
    public B otherItem;

    public Foo(ParentType parent, B otherItem) {
        this.parent = parent;
        this.otherItem = otherItem;
        Object b = parent.b;
    }
}

但是,这不允许我确保 bB,并且我希望强制执行,以便我可以将其传递给接受 B 的方法,例如。

我上一个问题的答案是添加更多模板,但我只能通过删除一些来编译代码。有没有我错过的技巧?

我知道我可以通过强制转换来解决这个问题,但如果可能的话,我希望编译器强制执行一个解决方案。

【问题讨论】:

    标签: java templates generics


    【解决方案1】:

    只将类型参数添加到参数化的类中,那么你应该实现你想要的:

    public class Foo<ParentType extends Parent<B>, B> {
        public ParentType parent;
        public B otherItem;
    
        public Foo(final ParentType parent, final B otherItem) {
            this.parent = parent;
            this.otherItem = otherItem;
            final B b = parent.b;
        }
    }
    

    现在 ParentType 必须是 Parent&lt;B&gt; 的子类型,因此 b 是 B 只要您的 ParentType 不覆盖它

    【讨论】:

    • 事后看来,这很有意义。我真的很感激!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多