java实现在运行时即时编译及执行代码

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);

}

}


版权声明:本文为connection_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。