作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试按照以下方式做一些事情:
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
在枚举中,不应该是这种情况。
如何变通?
谢谢!
最佳答案
C
不起作用,因为 Columns.RANK.type
在编译时不可访问。
但是,B
可以使用自定义的基于泛型的类而不是 enum
来实现:
class Columns<T>
{
public static final Columns<String> RANK = new Columns<String>(0, "Rank", String.class);
public static final Columns<Integer> NUMBER = new Columns<Integer>(1, "Number", Integer.class);
public final Class<T> type;
public final String text;
public final int index;
private Columns(int idx, String text, Class<T> clasz)
{
this.type = clasz;
this.text = text;
this.index = idx;
}
}
关于Java:使用枚举的动态类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2114287/
我是一名优秀的程序员,十分优秀!