1

我正在尝试开发一个插件,它从一个 java 文件生成测试和表类......当我选择一个 Java 源时,我将能够有一个选项“生成类测试”,这是我正在恢复 Java 的问题文件为ICompliationUnit,然后我有一个xtract对象的方法,这就是为什么;我想将其解析为IComplilationUnit代表的类的实例,我尝试使用Class.forName但它不起作用,这就是代码:

 private void write(String dir, ICompilationUnit cu) throws JavaModelException
   {

      try
      {
         cu.getCorrespondingResource().getName();
         System.out.println("0000000000000" + cu.getJavaProject().getProject().toString());
      }
      catch (JavaModelException e1)
      {
         // TODO Auto-generated catch block
         e1.printStackTrace();
      }
      String test = cu.getCorrespondingResource().getName();
      IPackageDeclaration[] test1 = cu.getPackageDeclarations();
      // Need
      String[] name = test.split("\\.");

      String contentFile = dir + "\\" + name[0] + "content.txt";
      GenerateFitnessTable inst = new GenerateFitnessTable();
      try
      {

         String pack = test1[0].toString().substring(7, test1[0].toString().indexOf("[") - 1) + "." + name[0];
         @SuppressWarnings("rawtypes")
         Class classe = Class.forName(cu.getJavaProject().getProject().toString()
                  .substring(cu.getJavaProject().getProject().toString().indexOf("/"), cu.getJavaProject().getProject().toString().length())
                  + pack);
         try
         {
            classe.newInstance();
         }
         catch (InstantiationException e)
         {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         catch (IllegalAccessException e)
         {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }

      catch (ClassNotFoundException e1)
      {
         System.out.print("****************************la classe n'existe pas");
      }
      try
      {
         inst.generateContent(cu, contentFile);
      }
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
4

1 回答 1

0

这是正确的方法;)),我找到了:

 // nouveau region
     region = JavaCore.newRegion();
     // ajout de la classe selectionné a cette region
     region.add(cu);

     if (JavaCore.getGeneratedResources(region, true).length == 0)
     {
        //  bug

     }
     // recuperer l'url de .class 
     String url = "file:" + JavaCore.getGeneratedResources(region, true)[0].getLocation().makeAbsolute();
     URL myUrl = new URL(url);
     URLConnection connection = myUrl.openConnection();
     InputStream input = connection.getInputStream();
     ByteArrayOutputStream buffer = new ByteArrayOutputStream();
     int data = input.read();

     while (data != -1)
     {
        buffer.write(data);
        data = input.read();
     }

     input.close();

     byte[] classData = buffer.toByteArray();

     clas = defineClass(pack.substring(1, pack.length()), classData, 0, classData.length);
于 2013-03-14T07:46:02.753 回答