我正在尝试将方法链与类扩展和在基类中定义的方法结合起来。但是,由于我对泛型还不太熟悉,因此我很难使它起作用。 有人可以帮我解决这个问题吗?我们将不胜感激。谢谢!
当前情况:
public abstract class A<T extends A<?>> extends F // the base class, all others extend this one (either direct or indirect)
public T isLoaded() { // method defined in class A
// Omitted
return (T) this;
}
public class B extends A<B> // One of the classes that extends the base class
public D tapButton() // Method defined in class B
public class C extends A<C> // Another class that extends the base class, also has a child itself
public C setAmount(int amount) // method defined in class C
public class D extends C // Class that extends the previous one (C)
public E tapButtonTwo() // Method defined in class D, can't move this one level up to due to other parts of the code
试图使用这些类和方法的代码:
// Failing scenario
protected void doSomething() {
// I already have an instance of type B, but I omitted this part
b.tapButton() // returns type D
.isLoaded() // returns type C and is the cause of the problem
.setAmount(10) // returns type C
.tapButtonTwo() // fails on: cannot resolve method
}
// Scenario that does work:
protected void doSomething() {
// I already have an instance of type B, but I omitted this part
b.tapButton() // returns type D
.setAmount(10) // now returns type D
.tapButtonTwo() // works
}