为此,您需要javax.tools
API。因此,您至少需要安装JDK才能使其正常运行(并让您的IDE指向它而不是JRE)。这是一个基本的启动示例(没有适当的异常和编码处理只是为了使基本示例不透明,不易
咳嗽 ):
public static void main(String... args) throws Exception { String source = "public class Test { static { System.out.println("test"); } }"; File root = new File("/test"); File sourceFile = new File(root, "Test.java"); Writer writer = new FileWriter(sourceFile); writer.write(source); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); compiler.run(null, null, null, sourceFile.getPath()); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); Class<?> cls = Class.forName("Test", true, classLoader);}这应该
test在stdout中打印,就像测试源代码中的静态初始化程序所做的那样。如果那些类实现了已经在类路径中的某个接口,则进一步使用将更加容易。否则,您需要使用Reflection
API来访问和调用方法/字段。



