我希望能够为一堆相关但不同的类读取和写入(获取和设置)某些字段,而不知道它们究竟是什么类型的具体类。我所知道的是,他们有一些类型的参数,我希望能够一般地访问和修改。鉴于我不知道班级的具体类型,我不知道每个班级的具体参数类型是什么。
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 ...
}
}
答案 0 :(得分:1)
使用Java界面来描述getter和setter。让所有具体类实现此接口。将对象转换为接口类型,并根据需要调用getter和setter。