假设我有一个接口和一些类:
public interface IPanel<ComponentType extends Component> {
public void addComponents(Set<ComponentType> components);
public ComponentType create();
}
public class Button extends Component { }
public class LocalizedButton extends Button { }
public class ButtonsPanel implements IPanel<Button> {
public void addComponents(Set<Button> components) { ... /* uses create() */ ; }
public Button create() { return new Button(); }
}
public class LocalizedButtonsPanel extends ButtonsPanel {
public Button create() { return new LocalizedButton(); }
}
然后我有一组LocalizedButtons,当我调用它们时:
final LocalizedButtonsPanel localizedButtonsPanel = new LocalizedButtonsPanel();
final Set<LocalizedButton> localizedButtonsSet = new LinkedHashSet<LocalizedButton>();
localizedButtonsPanel.addComponents(localizedButtonsSet);
我明白这种方法不适用于这些参数。 如果我尝试在
LocalizedButtonsPanel
中重载此方法为addComponents(Set<LocalizedButton> buttons)
,当然会得到类型擦除。也许有一些模式被忽略了或者存在处理这种架构以正确添加
LocalizedButtons
集合的技巧?
我已经得到了答案,并且想使我的示例更具体化-我在我的实现中有一些验证器,因此我需要将集合类型存储为泛型,这是使用答案简化的代码:
public interface IPanel<ComponentType extends Component, CollectionType extends Collection<? extends Component>> extends Validated<CollectionType> {
public void addComponents(CollectionType components);
public ComponentType create();
}
public class Button extends Component { }
public class LocalizedButton extends Button { }
public class ButtonsPanel implements IPanel<Button, Set<? extends Button>> {
public void addComponents(Set<? extends Button> components) { ... /* uses create() */ ; }
public Button create() { return new Button(); }
}
public class LocalizedButtonsPanel extends ButtonsPanel {
public Button create() { return new LocalizedButton(); }
}
在这种情况下,它是可行的。