Create .java file and compile it to a .class file at runtime

心已入冬 提交于 2019-12-01 10:02:00

问题


I'm generating a whole bunch of .java files from an XSD file using XJC. I also need to compile those files to .class files and use them at runtime via reflection.

The problem I'm having is that after I generate the .java files and try to compile them, the compiler can't compile them properly and gives me the following error:

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

I'm assuming this has to do with the fact that the JVM doesn't know about the package I just generated and as such can't find the referenced classes.

This can be solved by simply restarting the program after generating the .java files. But I'm curious if there's a way to do both steps during runtime without a restart.

I've looked at ways to "refresh" what packages are on the classpath at runtime, but with no luck.

This is the method I'm using to compile the files.

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());
    }
}

回答1:


So I finally figured this out...

Apparently you could pass several files to the compiler at once, and this solves the symbol error. What a stupidly simple solution.

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



回答2:


Have you tried looking up existing threads for the same topic ; On-the-fly, in-memory java code compilation for Java 5 and Java 6

for example.



来源:https://stackoverflow.com/questions/30912479/create-java-file-and-compile-it-to-a-class-file-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!