这个甘草啊,你也许没有理解楼主的意思。。type是一个字符串形式的类名,而value是一个字符串的值,也就是说要 看看这个字符串是否能转化为type中字符串对应类的对象。以我的理解应该是这个样子的 :)而你的代码中的value.getClass().toString()得出的应该是: class java.lang.String 而再indexOf(type)只是检查一下这个字符串里面是否有type中字符串诶~~我的理解应该采用反射获得type字符串所对应的class,再根据class,找出带有 String参数的构造,有的话说明可以转换,没有的话说明不能转换。
String type = "java.lang.Integer"; String value = "sss"; try{ Class cls = Class.forName(type); Class par[] = new Class[]{value.getClass()}; Object obj = cls.getDeclaredConstructor(par).newInstance(new Object[]{value}); System.out.println(obj);
String type = "Integer";
String value = "3333";
System.out.println(value.getClass().toString().indexOf(type) > 0);
看看这个字符串是否能转化为type中字符串对应类的对象。以我的理解应该是这个样子的 :)而你的代码中的value.getClass().toString()得出的应该是:
class java.lang.String
而再indexOf(type)只是检查一下这个字符串里面是否有type中字符串诶~~我的理解应该采用反射获得type字符串所对应的class,再根据class,找出带有
String参数的构造,有的话说明可以转换,没有的话说明不能转换。
String value = "sss";
try{
Class cls = Class.forName(type);
Class par[] = new Class[]{value.getClass()};
Object obj = cls.getDeclaredConstructor(par).newInstance(new Object[]{value});
System.out.println(obj);
}catch(Exception e){
System.out.println(e.toString());
}
int value=Integer.parseInt("12345");
} catch (NumberFormatException numberFormatException) {
Integer i = Integer.valueOf(value);
}
catch(Exception e)
{}