我正在尝试采取以下措施:

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

    ...
}

列是一个内部枚举,如下所示:
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/

10-11 04:24