private void compileTheJavaSrcFile(String sourceCode, String className) {
try {
/1、源代码保存到文件中/
long n = ThreadLocalRandom.current().nextLong();
File file = new File("D:\\tmp\\"+n);
file.mkdirs();
File files = new File(file, className+".java");
FileOutputStream out = new FileOutputStream(files);
out.write(codc.getBytes("GBK"));
out.flush();
out.close();
/
/2、编译代码
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, fileMgr.getJavaFileObjects(files));
t.call();
fileMgr.close();
/
/3、类加载,需要使用自定义类加载器,并且指定上面编译路径为加载路径///
URLClassLoader lo = URLClassLoader.newInstance(new URL[] {new URL("file://D:/tmp/"+n+"/")});
Class clazz = lo.loadClass(className);
///
///4、执行代码/
Method m = clazz.getMethod("main");
m.invoke(null);
/
} catch (Throwable e) {
throw new RuntimeException("Fail to compile files [" + codc + "]", e);
}
}