[英]Generic configuration of unknown subtypes with differing getters setters
我希望能夠讀寫一堆相關但不同的類的某些字段, 而又不知道它們具體是什么類型的具體類 。 我所知道的是,它們具有一些我希望能夠普遍訪問和修改的參數類型。 而且由於我不知道該類是什么具體類型,所以我也不知道每個類的具體參數類型是什么。
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接口描述獲取器和設置器。 讓所有具體的類都實現此接口。 將對象強制轉換為接口類型,然后根據需要調用getter和setter。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.