Here我找到了一些很好的例子:
// 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".
问题:如果不写文件,是否可以实现完全相同的目标?
@Edit: 更确切地说:我知道如何从字符串编译(重载JavaFileObject)。但在这之后,我不知道如何加载该类。我可能错过了输出写入部分,但这也是我不想做的事情。
@ EDIT2 对于任何有兴趣的人,我创建了这个小项目来实现所讨论的功能:https://github.com/Krever/JIMCy
答案 0 :(得分:4)
好的,所以here是使用JavaCompiler
从String
输入进行编译的示例。 this file是它的核心。
在this file中,我加载了编译的类。您会注意到我还使用正则表达式检测包和类名。
关于输出,如果你想在内存中这样做,看来你可以实现自己的JavaFileManager
;但我从来没有尝试过!
请注意,您可以通过扩展ForwardingJavaFileManager
答案 1 :(得分:0)
不完全是你要求的,但Groovy的Java库使得从String编译和计算表达式变得容易。语法不同但与Java非常相似,因此如果您可以更改要编译的字符串,以便它们使用Groovy而不是Java,那么任务将非常简单。有关代码示例,请参阅Embedding Groovy。