【发布时间】:2009-09-03 20:20:42
【问题描述】:
所以,我有一些代码看起来差不多(为简洁起见截断 - 忽略诸如公共成员变量之类的东西):
public class GenericThingy<T> {
private T mValue;
public final T[] mCandidates;
public GenericThingy(T[] pCandidates, T pInitValue) {
mCandidates = pCandidates;
mValue = pInitValue;
}
public void setValue(T pNewValue) {
mValue = pNewValue;
}
}
public class GenericThingyWidget {
private final GenericThingy<?> mThingy;
private final JComboBox mBox;
public GenericThingyWidget (GenericThingy<?> pThingy) {
mThingy = pThingy;
mBox = new JComboBox(pThingy.mCandidates);
//do stuff here that makes the box show up
}
//this gets called by an external event
public void applySelectedValue () {
mThingy.setValue(mBox.getSelectedItem());
}
}
}
我的问题是 mThingy.setValue(mBox.getSelectedItem());调用会产生以下错误:
Generics.GenericThingy<capture#4-of ?> 类型中的方法setValue(capture#4-of ?) 不适用于参数(对象)
我可以通过从 GenericThingyWidget 中 mThingy 和 pThingy 的声明中删除 <?> 来解决这个问题 - 这给了我一个“GenericThingy 是原始类型。应该参数化对 GenericThingy 的引用”警告。
我也尝试将 setValue 调用替换为
mThingy.setValue(mThingy.mCandidates[mBox.getSelectedIndex()]);
我真的希望它可以工作,但这产生了一个非常相似的错误:
Generics.GenericThingy<capture#4-of ?> 类型中的方法setValue(capture#4-of ?) 不适用于参数(capture#5-of ?)
有没有办法做到这一点 生成“原始类型”警告(“未经检查的强制转换”警告我可以接受)并且不使 GenericThingyWidget 成为泛型类型?我想我可以将 mBox.getSelectedItem() 的返回值转换为某些东西,但我不知道那会是什么。
作为附加问题,为什么对 mThingy.setValue 的替换调用不起作用?
【问题讨论】: