Friday, July 4, 2008

Compile a Java source from inside a Java program

Here is sample program which shows how to compile Java source file from inside a Java program using JDK 6.

Sample Java Code

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.tools.JavaCompilerTool;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompilerTool.CompilationTask;

public class Compiler {

public static void main (String[] args) {
String sourceFile = "c:/Sample.Java";
JavaCompilerTool compiler = ToolProvider.getSystemJavaCompilerTool ();
StandardJavaFileManager fileManager =
compiler.getStandardFileManager (null);

// prepare the source file(s) to compile
List sourceFileList = new ArrayList ();
sourceFileList.add (new File (sourceFile));
Iterable compilationUnits =fileManager.getJavaFileObjectsFromFiles (sourceFileList);
CompilationTask task = compiler.getTask (null,fileManager, null, null, null, compilationUnits);
task.run ();
boolean result = task.getResult ();
if (result) {
System.out.println ("Compilation was successful");
} else {
System.out.println ("Compilation failed");
}
try {
fileManager.close ();
} catch (IOException e) {
}
}
}

Reference
http://www.java2s.com

0 Java Junction comments: