【发布时间】: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 基本上认为它是一个语法混乱,从第一个嵌套的 < 开始。
我尝试删除类模板声明中的<B> 部分:
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;
}
}
但是,这不允许我确保 b 是 B,并且我希望强制执行,以便我可以将其传递给接受 B 的方法,例如。
我上一个问题的答案是添加更多模板,但我只能通过删除一些来编译代码。有没有我错过的技巧?
我知道我可以通过强制转换来解决这个问题,但如果可能的话,我希望编译器强制执行一个解决方案。
【问题讨论】: