javaCompiler簡單來說就是一個用來調用java語言編譯器的接口,我們使用它可以實現對其他路徑下或者遠程代碼的編譯。
顯然我們可以實現這樣一種操作,將一串符合java語法的字符串寫入一個java文件中。然后利用javaCompiler編譯此文件。最后通過
反射的方法實現對此文件的運行(online judge)。
public static void main(String[] args) throws Exception {
/**
* 將 string 寫入Hello.java中
* 通過文件輸出流
*/
String string = "public class Hello { public static void main(String []args){System.out.println(\"Hello\");}}";
File file = new File("C:\\Users\\Administrator\\Desktop\\temp\\Hello.java");
if (!file.exists()) {
file.createNewFile();
}
byte[] bytes = string.getBytes();
FileOutputStream stream = new FileOutputStream(file);
stream.write(bytes, 0, bytes.length);
stream.close();
/**
* 編譯Hello.java
* 通過反射調用main函數實現函數的運行
*/
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
int result = javaCompiler.run(null, null, null, "C:\\Users\\Administrator\\Desktop\\temp\\Hello.java");
System.out.println(result == 0 ? "success" : "failure");
URL[] urls = new URL[]{new URL("file:/" + "C:/Users/Administrator/Desktop/temp/")};
URLClassLoader classLoader = new URLClassLoader(urls);
Class c = classLoader.loadClass("Hello");
System.out.println(c.getName());
Method method = c.getDeclaredMethod("main", String[].class);
method.invoke(null, (Object) new String[]{"aa","bb"});
}
