将java编译为class文件,创建.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.

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

}

}

解决方案

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值