【发布时间】:2010-01-22 01:15:52
【问题描述】:
我正在尝试按照以下方式做一些事情:
public void setContents(Object[] values)
{
...
//A. this works
mRank =
((String)(values[Columns.RANK.index]));
//B. doesn't work (entire line underlined by netbeans)
mRank =
(Columns.RANK.type.cast(values[Columns.RANK.index]));
//incompatible types: required java,lang.String found: java.lang.Object
//C. doesn't work (first RANK is underlined by netbeans)
mRank =
((Columns.RANK.type)(values[Columns.RANK.index]));
//cannot find symbol symbol: class RANK location: blah.blah.Columns
...
}
其中 columns 是一个内部枚举,如下所示:
public static enum Columns
{
RANK(0, "Rank", String.class),
NUMBER(1, "Number", Integer.class);
public String text;
public Class type;
public int index;
private Columns(int idx, String text, Class clasz)
{
this.type = clasz;
this.text = text;
this.index = idx;
}
}
我明白为什么B 行不起作用,但我不明白为什么C 不起作用。如果我在类型转换之外的任何其他地方使用Columns.RANK.type,它工作正常,但是我尝试对类进行类型转换,它编译说它在枚举中找不到RANK,这不应该是案例。
如何解决?
谢谢!
【问题讨论】:
-
JDK7 中的
javac将对您的原始Class类型发出 rawtypes lint 警告,这应该会使此类问题更加明显。