动态编译源文件时如何向JavaCompiler提供接口?
我试图在运行时编译并加载一个类,而不知道该类的包。我确实知道该类应该符合接口以及源的位置(以及类名称)。我正在尝试以下操作:
/* Compiling source */
File root = new File("scripts");
File sourceFile = new File(root, "Test.java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath());
Test.java 文件看起来像
import foo.Itest;
public class Test implements Itest{
...
}
这样 我从编译器收到 cannot find symbol symbol : class Itest
错误。如何向编译器提供接口(已加载)以避免此错误?
[编辑 - 已解决]:错误来自于接口是 ITest
并且源引用了 Itest
接口。
I'm trying to compile and load a class at runtime, without knowing the package of the class. I do know that the class should comply with an interface, and the location of the source, (and hence the class name). I'm trying the following:
/* Compiling source */
File root = new File("scripts");
File sourceFile = new File(root, "Test.java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath());
where the Test.java file looks something like
import foo.Itest;
public class Test implements Itest{
...
}
And I get a cannot find symbol symbol : class Itest
error from the compiler. How do I provide the compiler with the interface (which has already been loaded) to avoid this error?
[EDIT - RESOLVED]: The error came from the fact the the interface was ITest
and the source referred to an Itest
interface.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来compiler.run() 可能是在外部运行并且需要设置类路径。您是否尝试过使用最后一个参数
args
向run()
调用传递合适的类路径设置?也许这就是ToolProvider.getSystemToolClassLoader()
的原因。这篇stackoverflow帖子可能也帮助你。
It seems likely that the
compiler.run()
is running externally and needs the class path to be set. Have you tried to pass it a suitable class path setting using the last parameterargs
to therun()
call? Perhaps that's whyToolProvider.getSystemToolClassLoader()
.This stackoverflow post might also help you.
不确定这是否是您正在寻找的,但是正如 @Phil 此处,您可以尝试在
compiler.run
方法中传递类路径参数。Not sure if this is what you're looking for but, as mentioned by @Phil here, you could try to pass a classpath argument in your
compiler.run
method.您是否考虑过使用 javassist 或类似的东西生成您的类?
Have you considered generating your class with javassist or something like that?