How to compile .java file from within java program

2019-03-06 19:27发布

Possible Duplicate:
Compiling external .java files from within Java

I have been using examples from all over the net but I keep getting NullPointerExceptions when invoking the run method in JavaCompiler. If you know how to compile another java file from within a java file please provide code on how to do this. Thanks

3条回答
在下西门庆
2楼-- · 2019-03-06 19:50

From the documentation for the STBC (which uses the JavaCompiler).

The docs for getSystemJavaCompiler() mention that it returns "the compiler provided with this platform or null if no compiler is provided", but do not make clear why it might be null, nor the fact that the compiler will not be available to applets or webstart apps. ..

It will be null if the code is run in a non SDK JRE (see explanation in the System Requirements).

查看更多
老娘就宠你
3楼-- · 2019-03-06 19:58

I already used JavaCompiler to compile math expressions on the fly.

Here is how I did it:

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();
查看更多
别忘想泡老子
4楼-- · 2019-03-06 20:04

You can use eclipse jdt compiler (http://www.eclipse.org/jdt/core). It is used in many projects to compile java.

Here is an example how tomcat uses it to compile servlets to .class: http://www.docjar.com/html/api/org/apache/jasper/compiler/JDTCompiler.java.html

查看更多
登录 后发表回答