The_Zykanator
The_Zykanator

Reputation: 43

How to compile .java file from within java program

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.

Upvotes: -1

Views: 6023

Answers (3)

Andrew Thompson
Andrew Thompson

Reputation: 168795

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).

Upvotes: 1

user1078394
user1078394

Reputation: 1

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

Upvotes: 0

GETah
GETah

Reputation: 21409

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();

Upvotes: 3

Related Questions