这里我找到了一些很好的例子:
// 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".
问题: 是否可以不写入文件而达到完全相同的效果?
@编辑:
更确切地说:我知道如何从字符串编译 (重载JavaFileObject),但在这之后,我不知道如何加载类。我可能错过了输出写入部分,但这也是我不想要的事情。
@Edit2
对于任何感兴趣的人,我创建了这个小项目来实现所讨论的功能: https://github.com/Krever/JIMCy