stuart
stuart

Reputation: 2293

Java: Dynamically cast Object reference to reference's class?

Is it possible to cast a variable using a different variable instead of using the name of a class?

Here is functioning code:

Object five = new Integer(5);
int six = (Integer) five + 1;

I would love to replace that second line with

int six = five + 1;

but I can't, so could i do something like one of these alternatives:

int six = (foo) five + 1;
int six = foo(five) + 1;
int six = foo.cast(five) + 1;

??

why i want to do this
I have a Map with keys of a custom enum, and with values of type String, Integer, Double, etc.

I would like to perform class-specific operations on map entry values without hard-coding the cast class.

example

enum keyEnum { height, color; }

public static void main(String[] args) {
    Map<keyEnum, Object> map= new HashMap();
    String value1 = "red";
    Double value2 = 3.2;
    map.put(keyEnum.color, value1);
    map.put(keyEnum.height, value2);

    double x = (Double) map.get(keyEnum.height) + 10.5;
}

I would really like to avoid having to hard-code that (Double) in the last line. Have found no solutions so far, only indications that it might not be possible.

I'm using this setup for a program that needs to write and read and write large csv files. I would like a way for Java to automatically cast variables appropriately so I don't have to remember or code the class of every column type.

I have an enum of all the column titles which i use as keys for maps that store the column's variables. This is to avoid hard-coding the array index for each column (after row.split(",")) which is a maintenance nightmare. I'm open to better approaches to this

Upvotes: 0

Views: 1875

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533880

You are not using Java as it was intended so it's going to be slow, unsafe and ugly. What you should do is

class MyType { double height; String color; }

public static void main(String[] args) {
    MyType mt = new MyType();
    mt.color = "red";
    mt.height = 3.2;

    double x = mt.height;

    // to iterate over the fields
    for(Field field: MyType.class.getDeclaredFields()) {
        System.out.println(field.getName() + "= "+ field.get(mt));
    }
}

This will be much safer with compile time checks, use less code and it will use far less memory and CPU.

Upvotes: 2

Samhain
Samhain

Reputation: 1765

Store the classtype in a variable, and leverage the cast method.

Class<T> cls and cls.cast()

Upvotes: 1

Related Questions