假如定义了一个String类型变量:String str = “abc” ; 我想把str变为List对象,即“abc”为此List变量名有不有什么办法?谢过!!!

解决方案 »

  1.   

    2个方法:第一种:
    Map map = new HashMap();
    List list = new ArrayList();
    map.put(str, list);第二种:
    反射
    有个copy来的代码,你可以参考看下
    import   java.lang.reflect.*;  
       
      class   Test{  
      private   int   pri   =   10;  
      protected   int   pro   =   20;  
      public   int   pub   =   30;  
      }  
      public   class   Demo{  
      public   static   void   main(String[]   args)    
      throws   IllegalAccessException{  
              Class   c   =   Test.class;      
                       
              Field[]   fs   =   c.getDeclaredFields();  
              //设为可访问的  
              Field.setAccessible(fs,   true);  
              for(int   i   =   0;   i   <   fs.length;   i++){  
              System.out.println(fs[i].getName()   +    
              "   value   is   "   +   fs[i].getInt(new   Test()));          
              }  
              }  
      }
      

  2.   

    java是强类型的语言,每个变量都是明确的
    要么就 List abc = new ArrayList()没有 eval("List abc = new ArrayList()"); 的写法。