簡體   English   中英

標識調用基類靜態函數的子類

[英]Identifying the child class calling a base class static function

假設我有一個帶有函數foo的基類

public class Base
{
    protected static void foo()
    {
        // ToDo - what is the name of the child class calling me?
    }
}

至少一個子類包含一個調用foo靜態初始化程序

public class Child extends Base
{
    static
    {
        foo();
    }
}

foo()知道哪個子類調用了它? 我想我可以使用一種反射技術。

最簡單的方法是傳遞參數。 例如

public class Base {
    protected static void foo(Class<?> type) {
        if (type == Child.class) {

        }
    }
}

public class Child extends Base {
   static {
       foo(Child.class);
   }
}

但是,如果您需要執行依賴於子類的操作,那么我建議您尋找一種利用抽象方法和多態性的解決方案。

public Base {
    protected static void foo(Base child) {
        child.doFoo();
    }

    protected abstract void doFoo();
}

public Child extends Base {
    static {
        foo(new Child());
    }

    @Override
    protected void doFoo() {
        //do the child specific thing here
    }
}

您可以使用getClass方法獲取類,例如:

o.getClass()

另外,如果您有c類,並且需要檢查o是否是c的實例,則可以使用instanceof ,如下所示:

o instanceof c

干杯。

暫無
暫無

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

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