1

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

2 Answers 2

2

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.