java:如何将变量从一种类型动态转换为另一种类型? [英] java: How can I do dynamic casting of a variable from one type to another?

查看:53
本文介绍了java:如何将变量从一种类型动态转换为另一种类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对 Java 变量进行动态转换,转换类型存储在不同的变量中.

I would like to do dynamic casting for a Java variable, the casting type is stored in a different variable.

这是常规演员表:

 String a = (String) 5;

这就是我想要的:

 String theType = 'String';
 String a = (theType) 5;

这可能吗,如果可以,怎么办?谢谢!

Is this possible, and if so how? Thanks!

我正在尝试使用我收到的 HashMap 填充一个类.

I'm trying to populate a class with a HashMap that I received.

这是构造函数:

public ConnectParams(HashMap<String,Object> obj) {

    for (Map.Entry<String, Object> entry : obj.entrySet()) {
        try {
            Field f =  this.getClass().getField(entry.getKey());                
            f.set(this, entry.getValue()); /* <= CASTING PROBLEM */
        } catch (NoSuchFieldException ex) {
            log.error("did not find field '" + entry.getKey() + '"');
        } catch (IllegalAccessException ex) {
            log.error(ex.getMessage());         
        }
    }

}

这里的问题是一些类的变量是 Double 类型,如果收到数字 3,它会将其视为 Integer 并且我有类型问题.

The problem here is that some of the class' variables are of type Double, and if the number 3 is received it sees it as Integer and I have type problem.

推荐答案

关于您的更新,在 Java 中解决此问题的唯一方法是编写涵盖所有情况的代码,其中包含大量 ifelseinstanceof 表达式.您尝试做的事情看起来好像是用于使用动态语言进行编程的.在静态语言中,您尝试做的事情几乎是不可能的,人们可能会为您尝试做的事情选择一种完全不同的方法.静态语言不如动态语言灵活:)

Regarding your update, the only way to solve this in Java is to write code that covers all cases with lots of if and else and instanceof expressions. What you attempt to do looks as if are used to program with dynamic languages. In static languages, what you attempt to do is almost impossible and one would probably choose a totally different approach for what you attempt to do. Static languages are just not as flexible as dynamic ones :)

Java 最佳实践的好例子是 BalusC 的回答(即 ObjectConverter)和 Andreas_D 的回答(即Adapter代码>) 下面.

Good examples of Java best practice are the answer by BalusC (ie ObjectConverter) and the answer by Andreas_D (ie Adapter) below.

<小时>

这没有意义,在


That does not make sense, in

String a = (theType) 5;

a 的类型静态绑定为 String,因此动态转换为该静态类型没有任何意义.

the type of a is statically bound to be String so it does not make any sense to have a dynamic cast to this static type.

PS: 示例的第一行可以写成 Class;stringClass = String.class; 但仍然不能使用 stringClass 来转换变量.

PS: The first line of your example could be written as Class<String> stringClass = String.class; but still, you cannot use stringClass to cast variables.

这篇关于java:如何将变量从一种类型动态转换为另一种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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