我正在尝试将方法链接与类扩展和基类中定义的方法结合起来。但是,我很难让它工作,因为我对泛型还不是很熟悉。有人可以帮我让它工作吗?这将不胜感激。谢谢!
现在的情况:
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
}