【问题标题】:Compiling generated code and jar with JavaCompiler使用 JavaCompiler 编译生成的代码和 jar
【发布时间】:2015-11-24 01:00:55
【问题描述】:

我已经生成了可以在命令行上使用 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 code-generation java-compiler-api


【解决方案1】:

尝试在您的 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();    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2013-05-30
    • 2017-06-06
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多