创建 .java 文件并在运行时将其编译为 .class 文件
Create .java file and compile it to a .class file at runtime
我正在使用 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 不知道我刚刚生成的包,因此无法找到引用的 classes。
这可以通过在生成 .java 文件后简单地重新启动程序来解决。但是我很好奇是否有一种方法可以在运行时执行这两个步骤而无需重新启动。
我已经研究过 "refresh" 运行时 class 路径上的包的方法,但没有成功。
这是我用来编译文件的方法。
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());
}
}
您是否尝试过查找同一主题的现有讨论帖;
On-the-fly, in-memory java code compilation for Java 5 and Java 6
例如。
所以我终于想通了...
显然您可以一次将多个文件传递给编译器,这解决了符号错误。多么愚蠢的简单解决方案。
public static void compile(String... files) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, files);
}
我正在使用 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 不知道我刚刚生成的包,因此无法找到引用的 classes。
这可以通过在生成 .java 文件后简单地重新启动程序来解决。但是我很好奇是否有一种方法可以在运行时执行这两个步骤而无需重新启动。
我已经研究过 "refresh" 运行时 class 路径上的包的方法,但没有成功。
这是我用来编译文件的方法。
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());
}
}
您是否尝试过查找同一主题的现有讨论帖; On-the-fly, in-memory java code compilation for Java 5 and Java 6
例如。
所以我终于想通了...
显然您可以一次将多个文件传递给编译器,这解决了符号错误。多么愚蠢的简单解决方案。
public static void compile(String... files) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, files);
}