【发布时间】:2017-08-17 18:17:12
【问题描述】:
我有一个字符串值和一个具体类型的类对象。
所以我的问题是如何将字符串值转换为该类型?
看起来唯一可能的方法是做这样的事情:
private Object convertTo(String value, Class type) {
if(type == long.class || type == Long.class)
return Long.valueOf(value);
if(type == int.class || type == Integer.class)
return Integer.valueOf(value);
if(type == boolean.class || type == Boolean.class)
return Boolean.valueOf(value);
...
return value;
}
但这看起来很丑......有没有更好的方法来做到这一点?
【问题讨论】:
-
给我们看代码,用几行代码更容易理解
-
您的意思是“转换”吗?除了它实现的接口之外,您不能将 Java 字符串 cast 到任何东西。
-
看来我是在尝试转换,而不是强制转换。
标签: java reflection casting