I want to implement some kind of component system in Java.
There is an interface, called Form
interface Form<T> {
T getObject();
// ...
}
And I'd like to provide some abstract class called CompoundForm to assist building complex forms from simple forms.
User of CompoundForm needs to provide some description of each component using Component interface
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);
}
Given this interface CompoundForm implementation is something like:
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;
}
}
Is it possible to implement something like this in type-safe manner without unchecked casts? Is my usage of wildcards correct?