我想对Java变量进行动态转换,转换类型存储在其他变量中。
这是常规转换:
String a = (String) 5;
这就是我要的:
String theType = 'String';
String a = (theType) 5;
可能吗?如果可以,怎么办?谢谢!
更新
我正在尝试使用收到的hashMap填充类。
这是构造函数:
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,而我遇到类型问题。
跃然一笑
神不在的星期二
大话西游666
相关分类