简体   繁体   English

Java:将对象引用动态转换为引用的类吗?

[英]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. 我有一个带有自定义枚举键的Map,其值类型为String,Integer,Double等。

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. 我真的希望避免在最后一行中对(Double)进行硬编码。 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. 我将此设置用于需要读写大型csv文件的程序。 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. 我想让Java适当地自动转换变量,这样就不必记住或编写每种列类型的类了。

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. 这是为了避免对每一列(在row.split(“,”)之后)进行硬编码,这是维护的噩梦。 I'm open to better approaches to this 我愿意采取更好的方法

You are not using Java as it was intended so it's going to be slow, unsafe and ugly. 您没有按预期使用Java,因此它将变得缓慢,不安全且丑陋。 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. 通过编译时检查,这将更加安全,使用更少的代码,并且使用更少的内存和CPU。

Store the classtype in a variable, and leverage the cast method. 将类类型存储在变量中,并使用强制转换方法。

Class<T> cls and cls.cast() Class<T> clscls.cast()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM