【发布时间】:2018-05-31 17:53:52
【问题描述】:
我正在开发一个 Web 项目,在该项目中我创建了一个自定义 .java 文件,使用自定义 ClassLoader 加载它,使用 Compiler API 编译它,然后通过反射执行它。唯一似乎不起作用的是编译看起来像这样的文件:
package testfiles;
import exceptions.IncorrectSolutionException;
public class TestFile {
public static void testSolution() throws IncorrectSolutionException {
//some code here
}
}
使用 Compiler-API 的诊断收集器,我收到以下错误消息:
package exceptions does not exist, line 2 cannot find symbol
symbol: class IncorrectSolutionException
包“异常”和引用的类肯定存在,我的 src 文件夹的结构是这样的:(包含类文件的文件夹)
- 源
- 例外情况
- 测试文件
我尝试按照here 的建议设置类路径,但没有任何改变。
我如何编译文件:
DiagnosticCollector< JavaFileObject > diagnostics = new DiagnosticCollector<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, files);
File file = new File(absolute path);
//I am using the absolute path here, because I had problems resolving the relative path as my working directory seems to be the folder eclipse is installed in.
Iterable<? extends JavaFileObject> files = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(file));
if(task.call()) {
System.out.println("compiling File");
} else {
//...handle Diagnostics
}
我是否必须向 CompilationTask 添加另一个选项,或者问题出在其他地方? 提前致谢!
【问题讨论】:
标签: java import package java-compiler-api