日期:2014-05-20  浏览次数:20780 次

已知一个类名的字符串,如何转换成对应类型?
比如,我有一个类型字符串java.lang.Integer, 有一个字符串"123"
String className = "java.lang.Integer";
String value="123";


如何让value转换成Integer类型的?

------解决方案--------------------
如果用反射:
public class Test {
public static void main(String[] args){
String className = "java.lang.Integer";
String value = "123";
try {
Class c = Class.forName(className);
Method m = c.getMethod("parseInt", value.getClass());
Integer i = (Integer)m.invoke(className.getClass() , value);
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
}
不用反射:Integer i = Integer.parseInt(value);
------解决方案--------------------
common-beanutils.jar里有个ConvertUtils.convert完全可以实现
以你的为例
Java code

for (String str : map.keySet()) {
            String type = map.get(str);
            try {
                Class clazz = Class.forName(type);
                Object returnObj = ConvertUtils.convert(str, clazz); 
                System.out.println(returnObj);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

------解决方案--------------------
Integer i = Integer.parseInt(value)
------解决方案--------------------
探讨
Integer i =  Integer.parseInt(value)

------解决方案--------------------
Class clazz = Class.forName("java.lang.Integer");
Object o = clazz.newIntance();
Field field = o.getField("value");
field.setAccessable(true);
field.set(o, 123);

Integer intValue = (Integer)o;
------解决方案--------------------
探讨
Class clazz = Class.forName("java.lang.Integer");
Object o = clazz.newIntance();
Field field = o.getField("value");
field.setAccessable(true);
field.set(o, 123);

Integer intValue = (Integer)o;

------解决方案--------------------
Integer.parseInt(value)
反射对象,一句话就行了
Integer inte = Class.forName("java.lang.Integer").newInstance();
------解决方案--------------------
对..就是反射..动态生成实例..先转成字节码再去实例化..