java - 基于参数在父类中使用子类的静态成员
问题描述
我想在多个类中使用相同的静态数据成员,并创建一个父类,我可以根据参数从特定类中调用变量。请参考代码。
对于下面的代码,我的要求是如果我打电话
Test.x
给出某种论点说Test1
or 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;
}
解决方案
不幸的是,静态和继承存在几个问题。
基于类的自定义配置最好在数据(属性、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() {
}
}
在构造函数中调用配置提供者有一个小缺陷:子类字段仍然不可用,但无论如何您都不想使用单个对象。
推荐阅读
- node.js - 如何在 Rest 上转换 Decimal128 值
- sql - SQL 查询需要 15 到 20 秒
- java - 不使用 join() 和 java.util.concurrent 的数组的多线程求和
- php - 引导框对话框窗口不显示
- java - 如何设置休眠查询超时
- amazon-web-services - 向存储桶策略 s3 添加权限的问题
- flutter - 颤振评估 var 是整数还是字符串
- reactjs - 单击reactjs中的复制按钮时如何创建工具提示“复制到剪贴板”
- content-management-system - TYPO3 @dontverifyrequesthash
- arrays - 用 ruby 删除数组中的下一个元素