我一直在使用来自全网的示例,但在JavaCompiler中调用run方法时,我一直得到NullPointerExceptions。如果您知道如何从java文件中编译另一个java文件,请提供有关如何执行此操作的代码。感谢
答案 0 :(得分:3)
我已经使用JavaCompiler动态编译数学表达式。
我是这样做的:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList("YouFileToCompile.java"));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null,
null, compilationUnits);
boolean success = task.call();
fileManager.close();
答案 1 :(得分:1)
来自documentation for the STBC(使用JavaCompiler
)。
getSystemJavaCompiler()
的文档提到它返回“此平台提供的编译器,如果没有提供编译器,则返回null
”,但不清楚为什么它可能会是null
,也不是编译器不适用于applets或webstart应用程序的事实。 ..
如果代码在非SDK JRE中运行,则为null
(请参阅System Requirements中的说明)。
答案 2 :(得分:0)
您可以使用eclipse jdt编译器(http://www.eclipse.org/jdt/core)。它在许多项目中用于编译java。
以下是tomcat如何使用它将servlet编译为.class的示例:http://www.docjar.com/html/api/org/apache/jasper/compiler/JDTCompiler.java.html