使Java父类方法返回子类的对象的方法

Tim*_*kov 31 java generics

当从子类对象调用此方法时,是否有任何优雅的方法使Java方法位于子类的父类返回对​​象中?

我想在不使用其他接口和额外方法的情况下实现它,并且在没有类强制转换,辅助参数等的情况下使用它.

更新:

对不起,我不太清楚.

我想实现方法链接,但我对父类的方法有问题:当我调用父类方法时,我无法访问子类方法... 我想我已经提出了我的想法的核心.

所以方法应该返回类的this对象this.getClass().

Gar*_*owe 64

如果您只是在寻找针对已定义子类的方法链接,那么以下内容应该有效:

public class Parent<T> {

  public T example() {
    System.out.println(this.getClass().getCanonicalName());
    return (T)this;
  }
}
Run Code Online (Sandbox Code Playgroud)

如果你愿意,它可以是抽象的,然后是一些指定泛型返回类型的子对象(这意味着你无法从ChildA访问childBMethod):

public class ChildA extends Parent<ChildA> {

  public ChildA childAMethod() {
    System.out.println(this.getClass().getCanonicalName());
    return this;
  }
}

public class ChildB extends Parent<ChildB> {

  public ChildB childBMethod() {
    return this;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你就像这样使用它

public class Main {

  public static void main(String[] args) {
    ChildA childA = new ChildA();
    ChildB childB = new ChildB();

    childA.example().childAMethod().example();
    childB.example().childBMethod().example();
  }
}
Run Code Online (Sandbox Code Playgroud)

输出将是

org.example.inheritance.ChildA 
org.example.inheritance.ChildA 
org.example.inheritance.ChildA 
org.example.inheritance.ChildB 
org.example.inheritance.ChildB
Run Code Online (Sandbox Code Playgroud)

  • 应该是Parent &lt;T扩展Parent &lt;T &gt;&gt;,不是吗? (2认同)

Gui*_*ume 7

你想要实现什么目标?这听起来不错.父类不应该知道它的孩子.它似乎非常接近打破Liskov替代原则.我的感觉是,通过改变一般设计可以更好地服务于您的用例,但如果没有更多信息则很难说.

对不起听起来有点迂腐,但是当我读到这样的问题时,我有点害怕.