【发布时间】:2020-10-02 06:44:12
【问题描述】:
我有一个奇怪的问题,我无法理解。我猜是因为我不熟悉泛型。
public abstract class AbstractClass <T extends AbstractClass <T>> {
//...
public <T extends AbstractClass> T genericMethod(){
//do stuff
return (T) this;
}
}
不要在非抽象类中使用它
public class MyClass extends AbstractClass <MyClass> {
//...
public void anotherMethod() {
//do other stuff
}
}
到目前为止或多或少还可以(也许不理想,但还可以)。现在令人困惑的部分:
private MyClass stubWithMyClassAsReturnValue(){
//more stuff
return new MyClass();
}
public void test1(){
MyCalss myClass = stubWithMyClassAsReturnValue().genericMethod();
myClass.anotherMethod();
//---> works just fine
}
public void test2(){
stubWithMyClassAsReturnValue().genericMethod().anotherMethod();
//---> compiling error because AbstractClass does not know about anotherMethod(),
// so genericMethod() returns AbstractClass and not MyClass
}
我猜有某种隐式转换。如何让代码更流畅,摆脱这个多余的“myClass”?我很确定有一个明显的错误,但我没有看到。
【问题讨论】:
-
你的案例是described here在类型参数的更多技巧标题下,但整篇文章值得一读
-
@pafauk。谢谢你,但你链接到这个页面。:)
-
哎呀,here it is。现在应该可以工作了:)