2012-02-02 176 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