2012-02-02 130 views
5

您好我有要求创建,编译和加载Java类运行时。使用FTL我创建java源文件,并且如果没有动态依赖关系,就能够编译源代码。使用Java编译器API来编译多个java文件

为了详细说明一个实例,我有两个java源文件,一个接口和它的实现类。我能够编译使用Java编译器API如下

String classpath=System.getProperty("java.class.path"); 
     String testpath =classpath+";"+rootPath+"/lib/is_wls_client.jar;"+rootPath+"/rtds_wls_proxyclient.jar;.;"; 
     File javaFile = new File(javaFileName+".java"); 
     JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
     List<String> optionList = new ArrayList<String>(); 
     optionList.addAll(Arrays.asList("-classpath",testpath)); 
     StandardJavaFileManager sjfm = compiler.getStandardFileManager(null, null, null); 
     Iterable fileObjects = sjfm.getJavaFileObjects(javaFile); 
     JavaCompiler.CompilationTask task = compiler.getTask(null, null, null,optionList,null,fileObjects); 
     task.call(); 
     sjfm.close(); 

我设置静态类,其已经在classpath类路径的界面,但是这种方法不用于动态创建类的工作?任何自定义类加载器都可以修复?我的最终实施将是在网络/应用服务器

任何反馈将得到高度赞赏

Satheesh

回答

6

我能够通过编译所有的java来解决这个问题的文件一起。使用FTL我生成Java类,然后使用Java编译器API和负载类进行自定义的类装载器编译

的Java编者

private void compile(File[] files) throws IOException{ 
     String classpath=System.getProperty("java.class.path"); 
     String rootPath=getServletContext().getRealPath("/"); 
     System.out.println("--> root Path "+rootPath); 
     String testpath=classpath+";.;xx.jar;yy.jar"; 
     JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
     List<String> optionList = new ArrayList<String>(); 
     optionList.addAll(Arrays.asList("-classpath",testpath)); 
//  optionList.addAll(Arrays.asList("-d",rootPath+"/target")); 
     StandardJavaFileManager sjfm = compiler.getStandardFileManager(null, null, null); 
     Iterable fileObjects = sjfm.getJavaFileObjects(files); 
     JavaCompiler.CompilationTask task = compiler.getTask(null, null, null,optionList,null,fileObjects); 
     task.call(); 
     sjfm.close(); 

    } 

下面的代码片段展示了如何使用自定义的类装载器

class CustomClassLoader extends ClassLoader { 

    public CustomClassLoader(ClassLoader parent) { 
      super(parent); 
    } 

    public Class findClass(String className,String path) { 
     byte[] classData = null; 
     try { 
      FileInputStream f = new FileInputStream(path); 
      int num = f.available(); 
      classData = new byte[num]; 

      f.read(classData); 
     } catch (IOException e) { 
      System.out.println(e); 
     } 
     Class x = defineClass(className, classData, 0, classData.length); 
     return x; 
    } 
} 

感谢 Satheesh

+0

定义一个类后,您需要解决它。 – 2015-12-17 16:14:25