小编典典

创建.java文件,并在运行时将其编译为.class文件

java

我正在使用XJC从XSD文件生成一堆.java文件。我还需要将这些文件编译为.class文件,并在运行时通过反射使用它们。

我遇到的问题是,在生成.java文件并尝试对其进行编译之后,编译器无法正确地对其进行编译,并给我以下错误:

.\src\com\program\data\ClassOne.java:44: error: cannot find symbol
    protected List<ClassTwo> description;
                   ^
  symbol:   class ClassTwo
  location: class ClassOne

我假设这与JVM不了解我刚刚生成的包,因此找不到引用的类有关。

这可以通过在生成.java文件后重新启动程序来解决。但是我很好奇,是否有一种方法可以在运行时执行两个步骤而无需重新启动。

我已经研究了在运行时“刷新”类路径上哪些包的方法,但是没有运气。

这是我用来编译文件的方法。

public static void compile(Path javaPath, String[] fileList) {
    for (String fileName : fileList) {
        Path fullPath = Paths.get(javaPath.toString(), fileName);

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        compiler.run(null, null, null, fullPath.toString());
    }
}

阅读 237

收藏
2020-11-23

共1个答案

小编典典

所以我终于想通了…

显然,您可以一次将多个文件传递给编译器,这可以解决符号错误。多么愚蠢的简单解决方案。

public static void compile(String... files) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, files);
}
2020-11-23