gpt4 book ai didi

Java:使用枚举的动态类型转换

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:15:36 25 4
gpt4 key购买 nike

我正在尝试按照以下方式做一些事情:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com