知道 String type = "Integer",  知道 String value = "sss"  如何能用type 和value 判断  sss 能否能转化为 Integer对象?

解决方案 »

  1.   

    需要知道完整的类名,如:java.lang.Integer,采用反射生成对象。
      

  2.   

    晕死, 

    String type = "Integer";
    String value = "3333";

    System.out.println(value.getClass().toString().indexOf(type) > 0);
      

  3.   

    这个甘草啊,你也许没有理解楼主的意思。。type是一个字符串形式的类名,而value是一个字符串的值,也就是说要
    看看这个字符串是否能转化为type中字符串对应类的对象。以我的理解应该是这个样子的 :)而你的代码中的value.getClass().toString()得出的应该是:
    class java.lang.String
    而再indexOf(type)只是检查一下这个字符串里面是否有type中字符串诶~~我的理解应该采用反射获得type字符串所对应的class,再根据class,找出带有
    String参数的构造,有的话说明可以转换,没有的话说明不能转换。
      

  4.   

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

    }catch(Exception e){
    System.out.println(e.toString());
    }
      

  5.   

    6楼用反射解决了。但你如果只想将字符转为数值,JDK已经有很多方法了:try {
           int value=Integer.parseInt("12345");
    } catch (NumberFormatException numberFormatException) {
      

  6.   

    try{
         Integer i = Integer.valueOf(value);
       }
    catch(Exception e)
    {}