簡體   English   中英

使Java父類方法返回子類對象的方法

[英]Way to make Java parent class method return object of child class

當從子類對象調用此方法時,是否有任何優雅的方法使位於父類中的 Java 方法返回子類的對象?

我想在不使用額外接口和額外方法的情況下實現它,並且在沒有類轉換、輔助參數等的情況下使用它。

更新:

對不起,我不是很清楚。

我想實現方法鏈,但是我對父類的方法有問題:當我調用父類方法時,我無法訪問子類方法......我想我已經提出了我的想法的核心。

所以這些方法應該返回this.getClass()類的this對象。

如果您只是在尋找針對已定義子類的方法鏈接,那么以下方法應該有效:

public class Parent<T> {

  public T example() {
    System.out.println(this.getClass().getCanonicalName());
    return (T)this;
  }
}

如果您願意,這可以是抽象的,然后是一些指定通用返回類型的子對象(這意味着您無法從 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;
  }
}

然后你像這樣使用它

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();
  }
}

輸出將是

org.example.inheritance.ChildA 
org.example.inheritance.ChildA 
org.example.inheritance.ChildA 
org.example.inheritance.ChildB 
org.example.inheritance.ChildB

你想達到什么目的? 這聽起來是個壞主意。 父類不應該對其子類一無所知。 這似乎非常接近於打破Liskov 替換原則 我的感覺是,通過更改總體設計,您的用例會得到更好的服務,但如果沒有更多信息,就很難說。

抱歉聽起來有點迂腐,但當我讀到這樣的問題時,我有點害怕。

簡單演示一下:

public Animal myMethod(){
  if(this isinstanceof Animal){
     return new Animal();
  }
  else{

     return this.getClass().newInstance();
  }
}

您可以調用this.getClass()來獲取運行時類。

但是,這不一定是調用該方法的類(它甚至可以在層次結構的更下方)。

並且您需要使用反射來創建新實例,這很棘手,因為您不知道子類具有什么樣的構造函數。

return this.getClass().newInstance(); // sometimes works

我確切地知道你的意思,在 Perl 中有$class變量,這意味着如果你在子類上調用一些工廠方法,即使它沒有在子類中被覆蓋,如果它實例化了$class的任何實例是子$class的實例將被創建。

Smalltalk、Objective-C,許多其他語言都有類似的功能。

唉,Java 中沒有這樣的等效工具。

如果你使用 Kotlin,你可以創建一個擴展函數

abstract class SuperClass
class SubClass: SuperClass()

fun <T : SuperClass> T.doSomething(): T {
    // do something
    return this
}

val subClass = SubClass().doSomething()
public class Parent {
    public Parent myMethod(){
        return this;
    }
}
public class Child extends Parent {}

並像這樣調用它

       Parent c = (new Child()).myMethod();
       System.out.println(c.getClass());

這個解決方案是否正確? 如果是,那么它與#1 解決方案有何不同?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM