我现在的处境很尴尬。 我正在开发一个“Eclipse 插件”,它必须将 .java 文件“编译”为 .class 文件(甚至可能是 jar)。
我正在尝试使用 Java Compiler API为了做这样的事情:
public class Compiler {
private JavaCompiler _javaCompiler;
private StandardJavaFileManager _sjfm = null;
private Files[] _filesIn;
public Compiler()
{
_javaCompiler = ToolProvider.getSystemJavaCompiler();
_sjfm = _javaCompiler.getStandardFileManager(null, null, null);
}
public void CompileFiles(ArrayList<String> strings, String outputFolder)
{
//_javaCompiler.run
Iterable fileObject = _sjfm.getJavaFileObjectsFromStrings(strings);
String[] options = new String[]{"-d", outputFolder};
_javaCompiler.getTask(null, null, null, Arrays.asList(options), null, fileObject).call();
try {
_sjfm.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
问题是,当我调用 _sjfm = _javaCompiler.getStandardFileManager(null, null, null);
时,我遇到了 NullPointerException,因为这是不运行 JDK 时的“预期”行为(请引用此bug report)
这个StackOverflow post在某种程度上帮助了我,但是从必须可发布的 Eclipse 插件中编译 Java 文件的正确方法是什么?
- 使用替代“编译器”并仅包含 jar 并使用它们?
- 在我的插件中包含tools.jar(可在JDK 文件夹中找到),动态加载它并从中进行编译?
- 我想不出的任何其他解决方案
你会推荐什么?
最佳答案
您可以使用 Eclipse JDT 编译器,如 http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Fguide%2Fjdt_api_compile.htm 中所述。 .
关于java - 在 Eclipse Plugin 运行时编译 Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16950845/