我正在使用javax.tools包(JDK 1.7)中的JavaCompiler即时编译一些内容,如下所示:
compiler.run(null, null, "-cp", paths, "path/to/my/file.java");
它可以工作,但是我想在内存中完成所有操作(例如,传递带有代码的字符串,而不是源文件,并返回字节码而不是.class文件)。我发现扩展InputStream
和OutputStream
参数没有用,因为它可能与控制台中的相同。您知道一种使run方法像这样工作的方法吗?还是您知道使用该getTask()
方法的可靠方法?(扩展FileManager看起来很容易,但并不容易:)
我已经在Mac OS Java 7中运行了上面的代码。它们都不起作用。所以我写了一个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());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句