动态编译源文件时如何向JavaCompiler提供接口?

发布于 2024-09-13 10:44:51 字数 636 浏览 6 评论 0原文

我试图在运行时编译并加载一个类,而不知道该类的包。我确实知道该类应该符合接口以及源的位置(以及类名称)。我正在尝试以下操作:

/* 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

灼疼热情 2024-09-20 10:44:51

看起来compiler.run() 可能是在外部运行并且需要设置类路径。您是否尝试过使用最后一个参数 argsrun() 调用传递合适的类路径设置?也许这就是 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 parameter args to the run() call? Perhaps that's why ToolProvider.getSystemToolClassLoader().

This stackoverflow post might also help you.

感性不性感 2024-09-20 10:44:51

不确定这是否是您正在寻找的,但是正如 @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.

老旧海报 2024-09-20 10:44:51

您是否考虑过使用 javassist 或类似的东西生成您的类?

Have you considered generating your class with javassist or something like that?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文