首页 > 解决方案 > 基于参数在父类中使用子类的静态成员

问题描述

我想在多个类中使用相同的静态数据成员,并创建一个父类,我可以根据参数从特定类中调用变量。请参考代码。

对于下面的代码,我的要求是如果我打电话

Test.x给出某种论点说Test1or Test2,它应该让我从相应的类中获得价值。有人可以帮我吗?

我不想使用Builder(),CSV或实例化该类。有没有其他解决方案?

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

标签: javainheritancestatic

解决方案


不幸的是,静态和继承存在几个问题。

基于类的自定义配置最好在数据(属性、XML)中以声明方式完成,但也可以在代码中完成。基类可以保存所有子配置的映射。

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

构造函数中调用配置提供者有一个小缺陷:子类字段仍然不可用,但无论如何您都不想使用单个对象。


推荐阅读