使用javax.tools.JavaCompiler在内存中完全编译代码
我使用javax.tools包(JDK 1.7)中的JavaCompiler即时编译一些东西,如下所示:
I'm using the JavaCompiler from the javax.tools package (JDK 1.7) to compile some stuff on the fly, like this:
compiler.run(null, null, "-cp", paths, "path/to/my/file.java");
它可以工作,但我想在内存中做这一切(例如传递一个字符串的代码,不是源文件,并且获取字节代码不是一个.class文件)。我发现扩展 InputStream
和 OutputStream
参数没有用,因为它可能与在控制台中相同。你知道一种方法来使运行方法这样工作吗?或者你知道用 getTask()
方法确认的方法吗? (扩展FileManager看起来很容易,但不是那么容易:)
It works but I would like to do it all in memory (e.g. pass a string with the code, not the source file, and get the byte code back not a .class file). I found that extending the InputStream
and OutputStream
parameters is no use since it's probably just the same as in the console. Do you know a way to make the run method work like this? Or do you know a confirmed way to do this with the getTask()
method? (extending the FileManager looks easy but isn't that easy :)
我在Mac OS Java中运行上面的代码7.他们都没有工作。所以我写了一个
https://github.com/trung/InMemoryJavaCompiler
I've run the above code in Mac OS Java 7. None of them works. So i wrote one https://github.com/trung/InMemoryJavaCompiler
StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;\n");
sourceCode.append("public class HelloClass {\n");
sourceCode.append(" public String hello() { return \"hello\"; }");
sourceCode.append("}");
Class<?> helloClass = InMemoryJavaCompiler.compile("org.mdkt.HelloClass", sourceCode.toString());