簡體   English   中英

調用的靜態方法

[英]Calling the Static Method of

這有點不可思議,可能會導致語法不穩定,但我持保留態度。 我已經嘗試了三個月,並且堅信我需要一種方法來做到這一點:

public abstract class Sup{
    ...
    //This is implemented here because I cannot create an abstract static
    //only implemented by the children but called statically by methods in
    //the parent (more info later on in the post):
    protected static Class<? extends Sup> getTypeClass(){ return Sup.class };
    public static void init(){
        ...
        alreadyDeclaredHashMap.put(getTypeClass(), hashMapOfOtherStuff);
    }
}

public class A extends Sup{
    static{
        init();
    }
    protected static void getTypeClass(){ return A.class };
}
public class B extends Sup{
    static{
        init();
    }
    protected static void getTypeClass(){ return B.class };
}
... and so on.

因此,如果我要打印出已經為alreadyDeclaredHashMap ,它將看起來像:

    class A -> hashMapOfOtherStuff
    class B -> hashMapOfOtherStuff
    class C -> hashMapOfOtherStuff
    ...

但是,它打印:

    class Sup -> hashMapOfOtherStuff
    class Sup -> hashMapOfOtherStuff
    class Sup -> hashMapOfOtherStuff
    ...

因為擴展類隱藏了getTypeClass()但不能覆蓋它。 這只是一個例子。 實際上,我正在制作一個Units系統,並且我有很多方法取決於getTypeClass() ,並且真的很希望不必在每個擴展類(其中有不確定的數量)中重寫它們,而實現上唯一的不同是班級名稱。

非常感謝!

PS這些方法確實必須是靜態的,因為它們是靜態調用的(我寧願不必為了調用它們而創建虛擬實例或反射)。

沒有辦法使它起作用。 即使從其中一個調用init方法,類sup的靜態代碼也不知道A類和B類。

靜態方法不是“ 虛擬 ”的,因此從Sup的靜態代碼調用getTypeClass()將調用該實現,而不是任何子類實現。

現在,如果重用ABinit方法,則必須作為參數傳遞。

public abstract class Sup{
    ...
    public static void init(Class<? extends Sup> typeClass) {
        ...
        alreadyDeclaredHashMap.put(typeClass, hashMapOfOtherStuff);
    }
}

public class A extends Sup {
    static {
        init(A.class);
    }
}
public class B extends Sup {
    static {
        init(B.class);
    }
}

暫無
暫無

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

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