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

三世轮回 提交于 2019-12-12 01:05:50

问题


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


回答1:


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.




回答2:


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

Class<T> cls and cls.cast()



来源:https://stackoverflow.com/questions/21244993/java-dynamically-cast-object-reference-to-references-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!