我希望能够为一堆相关但不同的类读取和写入(获取和设置)某些字段而不知道它们到底是什么类型的具体类。我所知道的是,它们有一些我希望能够普遍访问和修改的参数类型。鉴于我不知道类的具体类型是什么,我也不知道每个类的具体参数类型是什么。
- 我认为以下方法可行,但它是否足够好/它可能存在什么问题?
- 或者针对此问题是否有更好的方法/甚至已建立的设计模式?
允许通用配置的父类(super class)
public abstract class ParametrizerBase<P1, P2> {
public P1 Param1;
public P2 Param2;
}
一些具有特定参数的具体类
public class SomeConcreteClass extends ParametrizerBase<Boolean, String> {
public SomeConcreteClass(Boolean enabled, String task){
Param1 = enabled;
Param2 = task;
}
// ... does something with the parameter data
}
另一个具有不同数据类型的具体类
public class AnotherConcreteClass extends ParametrizerBase<Integer, Date> {
public AnotherConcreteClass(Integer numberOfItems, Date when){
Param1 = numberOfItems;
Param2 = when;
}
// ... does something with the data it holds
}
示例用法
ArrayList<ParametrizerBase> list;
public void initSomewhere() {
SomeConcreteClass some = new SomeConcreteClass(true,"Smth");
AnotherConcreteClass another = new AnotherConcreteClass(5, new Date());
list = new ArrayList<ParametrizerBase>();
list.add(some);
list.add(another);
}
public void provideDataElsewhere() {
for (ParametrizerBase concrete : list) {
String param1Type = concrete.Param1.getClass().getName();
if (param1Type.contains("Boolean")) {
Boolean value = concrete.Param1;
// Now could let user modify this Boolean with a checkbox
// and if they do modify, then write it to concrete.Param1 = ...
// All without knowing what Param1 is (generic configuration)
} else if (param1Type.contains("Integer")) {
Integer value = concrete.Param1;
// ...
} // ...
// Same for Param2 ...
}
}
最佳答案
使用 Java 接口(interface)来描述 getter 和 setter。让所有的具体类实现这个接口(interface)。将对象转换为接口(interface)类型,并根据需要调用 getter 和 setter。
关于java - 具有不同 getters setter 的未知子类型的通用配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8457137/