使用 JavaCompiler 编译生成的代码和 jar

Compiling generated code and jar with JavaCompiler

我已经生成了可以在命令行上使用 javac 编译器编译的代码,如下所示:

javac generated/Buffer.java -classpath framework-core.jar

现在我正在尝试使用 JavaCompiler 自动执行测试中的编译。使用以下代码(来自 http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html):

String path = "/generated/Buffer.java";
File file = new File(System.getProperty("user.dir") + path);
File[] files1 = new File[]{file};
//HERE I WOULD LIKE TO GIVE framework-core.jar TO COMPILER

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files1));

compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();

fileManager.close();

如果我不提供 framework-core.jar 的类路径,我能够产生与从命令行得到的相同的错误。在使用编程 JavaCompiler 时,如何为该 jar 提供类路径?

我也想知道是否有更直接的方法来编译和运行生成代码。

尝试在您的 java 编译器上指定 classpath 选项:

List<String> optionList = new ArrayList<String>();
// set compiler's classpath to the path of your framework-core.jar
optionList.addAll(Arrays.asList("classpath","/lib/framework-core.jar"));
...
compiler.getTask(null, fileManager, null, optionList, null, compilationUnits1).call();