Java:动态转换对引用类的对象引用? [英] Java: Dynamically cast Object reference to reference's class?

查看:175
本文介绍了Java:动态转换对引用类的对象引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用不同的变量而不是使用类的名称来转换变量?

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

以下是函数代码:

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

我想替换第二行

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;

我想做这个

我有一个自定义枚举的键的映射,并且类型为String,Integer,Double等的值。

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



我真的想避免硬编码(Double)。到目前为止找不到解决方案,只有迹象表明它可能不可能。

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.

我使用这个设置程序,需要写和读写大csv文件。我想要一种方式让Java自动转换适当的变量,所以我不必记住或编码每个列类型的类。

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.

我有一个枚举所有列标题,我用作存储列的变量的地图的键。这是为了避免硬编码每个列(在row.split(,))后的数组索引,这是一个维护噩梦。我对这个更好的方法开放

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

推荐答案

你不是使用Java因为它的意图,不安全和丑陋。你应该做的是

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

这将是更安全的编译时检查,使用较少的代码,它将使用少得多的内存和CPU。

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

这篇关于Java:动态转换对引用类的对象引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆