创建.java文件,并在运行时将其编译为.class文件 [英] Create .java file and compile it to a .class file at runtime

查看:172
本文介绍了创建.java文件,并在运行时将其编译为.class文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我遇到的问题是,在生成.java文件和尝试编译它们,编译器无法正确编译它们,并给我以下错误:

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

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

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.

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

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


推荐答案

所以我终于弄清楚了……

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

这篇关于创建.java文件,并在运行时将其编译为.class文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆