Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Dynamic type casting using enums

I am trying to do something along the lines of:

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

    ...
}

Where columns is an inner enum, like so:

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;
    }
}

I understand why line B doesn't work, but what I don't get is why C doesn't work. If I use Columns.RANK.type anywhere else other than in a type cast, it works fine, but one I attempt to do a typecast with the class, it compiles saying it cannot find RANK in the enum, which shouldn't be the case.

How to work around?

Thanks!

like image 373
bguiz Avatar asked Jan 22 '10 01:01

bguiz


1 Answers

C doesn't work, because Columns.RANK.type is not accessible at compile time.

However, B can be implemented using a custom generic-based class instead of 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; 
    } 
}
like image 115
axtavt Avatar answered Oct 06 '22 04:10

axtavt