2013-02-14 85 views

回答

4

你可以使用JavaCompiler API來編譯這個類,它會讓你知道是否有一些編譯錯誤。

人爲的例子(使用一個字符串作爲輸入,但你可以閱讀文件,而不是):

String className = "somepackage.YourClass"; 
String body = "package somepackage; " 
       + "public class YourClass {   " 
       + "}        "; 
compile(className, body, TEMP_PATH); //TEMP_PATH: Where the .class file is saved 

其中編譯看起來是這樣的:

private static void compile(String className, String body, Path path) throws Exception { 
    List<JavaSourceFromString> sourceCode = Arrays.asList(new JavaSourceFromString(className, body)); 

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); 
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(path.toFile())); 
    boolean ok = compiler.getTask(null, fileManager, null, null, null, sourceCode).call(); 

    System.out.println("compilation ok = " + ok); 
} 
+0

+1另請參見示例。 [這裏](http://www.java2s.com/Code/Java/JDK-6/CompileaJavafilewithJavaCompiler.htm) – 2013-02-14 10:47:34