我想在Java中實現某種組件系統。使用Java通配符
有一個接口,稱爲表
interface Form<T> {
T getObject();
// ...
}
,我想提供一些所謂的CompoundForm協助從簡單的形式構建複雜的形式抽象類。 CompoundForm的
用戶需要使用組件的接口來提供每個組件的一些描述
interface Component<T, U> {
/** Factory method to build new form for given component */
Form<U> createForm(U u, String prefix);
/** Extract component of type U from the compound t */
U get(T t);
/** Mutate t or build new compound of type T using information from u */
T set(T t, U u);
}
鑑於此接口CompoundForm實現是一樣的東西:
abstract class CompoundForm<T> implements Form<T> {
/** User should override this method and provide a collection of
* actual components of different types, hence ? wildcard */
protected abstract Map<String, Component<T, ?>> componentMap();
private Map<String, Form<?>> formMap = new TreeMap<String, Form<?>>();
private final T object;
public CompoundForm(T object, String prefix) {
this.object = object;
for (Entry<String, Component<T, ?>> e: componentMap()) {
String subPrefix = e.getKey();
Component<T, ?> component = e.getValue();
// !!! Compile error here: type error
Form<?> form = component.createForm(component.get(object), prefix + subPrefix);
formMap.put(subPrefix, form);
}
}
public T getObject() {
T result = object;
for (Entry<String, Component<T, ?>> e: componentMap()) {
String subPrefix = e.getKey();
Component<T, ?> component = e.getValue();
Form<?> form = formMap.get(subPrefix);
// !!! Compile error here: type error
result = component.set(result, form.getObject());
}
return result;
}
}
是否有可能實現這樣的事情在類型安全的方式沒有未經檢查的強制轉換?我的通配符的用法是否正確?