动态编译源文件时如何为JavaCompiler提供接口? [英] How to provide an interface to JavaCompiler when compiling a source file dynamically?
问题描述
我试图在运行时编译和加载一个类,但不知道该类的包.我确实知道该类应该遵守接口和源的位置(以及类名).我正在尝试以下操作:
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());
Test.java 文件在哪里
where the Test.java file looks something like
import foo.Itest;
public class Test implements Itest{
...
}
我从编译器中得到一个 cannot find symbol symbol : class 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?
: 错误来自于接口是 ITest
并且源引用了 Itest
接口的事实.
: The error came from the fact the the interface was ITest
and the source referred to an Itest
interface.
推荐答案
compiler.run()
似乎很可能在外部运行,需要设置类路径.您是否尝试使用最后一个参数 args
将合适的类路径设置传递给 run()
调用?也许这就是 ToolProvider.getSystemToolClassLoader()
的原因.
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()
.
这个 stackoverflow 帖子 也可能对您有所帮助.
This stackoverflow post might also help you.
这篇关于动态编译源文件时如何为JavaCompiler提供接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!