Java组合和泛型类型
我尝试创建org.eclipse.swt.custom.CCombo类的组合 由于“项目”的原因,我不能继承CCOMO 当我想要检索所选数据元素时,目标是在任何地方都避免此代码:Java组合和泛型类型,java,generics,Java,Generics,我尝试创建org.eclipse.swt.custom.CCombo类的组合 由于“项目”的原因,我不能继承CCOMO 当我想要检索所选数据元素时,目标是在任何地方都避免此代码: MyElement selectedElement = (MyElement) myCombo.getData(Integer.toString(selectedIndex)); 组合框的填充方式如下: combo.setData(Integer.toString(myIndex), myObject); //
MyElement selectedElement = (MyElement) myCombo.getData(Integer.toString(selectedIndex));
组合框的填充方式如下:
combo.setData(Integer.toString(myIndex), myObject);
//MyElement is just an enum that implements IGenericComboList.
MyElement selectedElement = (MyElement)dateCombo.getSelectedData();
以下是迄今为止所做的工作:
public class GenericCCombo {
private CCombo combo;
public GenericCCombo(CCombo c) {
combo = c;
}
public IGenericComboList getSelectedData () {
return (IGenericComboList) combo.getData(String.valueOf(combo.getSelectionIndex()));
}
IGenericComboList就是这样:
public interface IGenericComboList {
public String getDescription();
}
因此,在我的实现代码中,我可以像这样检索我选择的数据:
combo.setData(Integer.toString(myIndex), myObject);
//MyElement is just an enum that implements IGenericComboList.
MyElement selectedElement = (MyElement)dateCombo.getSelectedData();
我的问题是:我是否可以在这里使用“泛型类型”来避免强制转换:
(MyElement)dateCombo.getSelectedData();
是的,这是可能的。使用泛型类型定义接口IGenericComboList
interface IGenericComboList<E> {
public String getDescription();
}
确保dateCombo.getSelectedData;返回IGenericComboList的元素您可以使用泛型类型参数声明GenericCmbo:
class GenericCCombo<T> {
public T getSelectedCombo() {
//...
}
}
如果您不确定可以返回哪个值,使泛型成为一个不好的选项,请查看。您不需要知道正在使用的对象的类型,而是将信息传递给对象并允许对象本身对其进行处理。是的,您可以在此处使用泛型,方法是在GenericCmbo上使用泛型参数。我建议您将传入元素的.class作为一个附加参数,并使用该参数再次检查您是否拥有正确的类:
public class GenericCCombo<E extends IGenericComboList> {
private CCombo combo;
private Class<E> clazz;
public GenericCCombo(CCombo c, Class<E> clz) {
combo = c;
clazz = clz;
}
public E getSelectedData () {
Object o = combo.getData(String.valueOf(combo.getSelectionIndex()));
if (! clazz.isInstance(o)) {
throw new ClassCastException(String.format(
"Element '%s' is instance of %s. Expected: %s",
o, o.getClass(), clazz));
}
return clazz.cast(o);
}
}
看看它的never clean——更好的解决方案是将您想要使用的特定方法放入接口中,这样您就不必知道底层实例是什么。getData可以返回IGenericComboList的其他实现吗?如果是这样的话,你怎么知道对MyElement施放是安全的?看起来这个问题的要点是“如何使用泛型”。看一看combo可以存储多种类型吗?即在不同的索引下有两种不同类型的类?这是一包混杂的东西吗