【问题标题】:Java Compiler API: import of custom package not workingJava Compiler API:自定义包的导入不起作用
【发布时间】: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


    【解决方案1】:

    显然它必须对工作目录和启动 Tomcat 的文件夹做一些事情。在服务器位置下配置服务器路径对我有用(将其设置为我工作区中的项目根目录)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 2017-09-08
      • 2010-10-12
      • 1970-01-01
      相关资源
      最近更新 更多