java 变量 动态类型,java:我怎么能动态转换变量从一种类型到另一种?

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

this is regular casting:

String a = (String) 5;

this is what i want:

String theType = 'String';

String a = (theType) 5;

is it possible? and if so how? thanks!

update

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

this is the constructor:

public ConnectParams(HashMap obj) {

for (Map.Entry 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());

}

}

}

the problem here is that some of the classes variables are Double type, and if the number 3 is received it sees it as Integer and i have type problem.

解决方案

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 :)

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;

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值