从String编译java源代码而不写入文件

Kre*_*ver 12 java

在这里,我找到了一些很好的例子:

// Prepare source somehow.
String source = "package test; public class Test { static { System.out.println(\"hello\"); } public Test() { System.out.println(\"world\"); } }";

// Save source in .java file.
File root = new File("/java"); // On Windows running on C:\, this is C:\java.
File sourceFile = new File(root, "test/Test.java");
sourceFile.getParentFile().mkdirs();
new FileWriter(sourceFile).append(source).close();

// Compile source file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath());

// Load and instantiate compiled class.
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
Class<?> cls = Class.forName("test.Test", true, classLoader); // Should print "hello".
Object instance = cls.newInstance(); // Should print "world".
System.out.println(instance); // Should print "test.Test@hashcode".
Run Code Online (Sandbox Code Playgroud)

问题:如果不写入文件,是否可以实现完全相同的功能?

@Edit: 更确切地说:我知道如何从字符串编译(重载JavaFileObject).但在这之后,我不知道如何加载该类.我可能错过了输出写入部分,但这也是我不想做的事情.

@ Edit2 对于任何有兴趣的人,我创建了这个小项目来实现所讨论的功能:https://github.com/Krever/JIMCy

fge*_*fge 4

好的,JavaCompiler是一个使用从输入进行编译的示例String这个文件是它的核心。

这个文件中,我加载了已编译的类。您会注意到我还使用正则表达式检测包和类名。


至于输出,如果您想在内存中执行此操作,那么如果您实现自己的输出,则似乎可以这样做JavaFileManager;但我从来没有尝试过!

请注意,您可以通过扩展来轻松调试发生的情况ForwardingJavaFileManager