簡體   English   中英

基於 arguments 在父 class 中使用子 class 的 static 成員

[英]Using static members of child class in parent class based on arguments

我想在多個類中使用相同的 static 數據成員,並創建一個父 class,我可以從中根據參數從特定的 class 調用變量。 請參考代碼。

對於下面的代碼,我的要求是如果我打電話

Test.x給出了某種參數,比如Test1Test2 ,它應該讓我從各自的 class 中得到值。 有人可以幫我嗎?

我不想使用Builder()CSV或實例化 class。 有沒有其他解決方案?

Class Test() {
    static int x;
    static int y;
    static int z;
}

Class Test1() {
    static int x = 1;
    static int y = 2;
    static int z = 3;
}

Class Test2() {
    static int x = 4;
    static int y = 5;
    static int z = 6;
}

不幸的是,static 和 inheritance 存在幾個問題。

基於 class 的自定義配置最好在數據(屬性、XML)中以聲明方式完成,但也可以在代碼中完成。 底座 class 可以容納所有兒童配置的 map。

class Base {

    private static Map<Class<T extends Base>, Config> configByClass = new HashMap<>();

    protected Base(Supplier<Config> configProducer) {
        // Could do in constructor:
        configByClass.merge(getClass(), (oldk, k) -> {
            if (oldk == null) {
                return configProducer.get();
            }
        });
    }

    protected final Config getConfig() {
        // Could do lazy in getter
        configByClass.merge(getClass(), (oldk, k) -> {
            if (oldk == null) {
                return configProducer.get();
            }
        });
        return configByClass.get(getClass());
    }
}

class Child1 extends Base {
    public Child1() {
        super(() -> {
            Config config = new Config(1, 3, 4);
            ...
            return config;
        });
    }

    void f() {
    }
}

構造函數中調用配置供應商有一個小缺陷:子 class 字段仍然不可用,但無論如何您都不想使用單個對象。

 public class test{ static int a; static int b; static int c; //to use the values of test1 class do this a = test1.a; b = test1.b; c = test1.c; //to use the values of test2 class do this a = test2.a; b = test2.b; c = test2.c; } public class test1{ static int a = 1; static int b = 2; static int c = 3; } public class test2{ static int a = 4; static int b = 5; static int c = 6; }

希望這可以幫助

暫無
暫無

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

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