Hey everybody,
Well, I was trying to compile a piece of java code from within java program itself.
But, I am having some trouble with this example code which I am learning from:
Here is the code:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
public class JVMComp {
public static void main (String[] args) {
String sourceFile = "c:/HelloWorld.Java";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
// prepare the source file(s) to compile
List<File> sourceFileList = new ArrayList <File> ();
sourceFileList.add (new File (sourceFile));
Iterable<? extends JavaFileObject> compilationUnits =fileManager.getJavaFileObjectsFromFiles (sourceFileList);
CompilationTask task = compiler.getTask (null,fileManager, null, null, null, compilationUnits);
boolean result = task.call();
if (result) {
System.out.println ("Compilation was successful");
} else {
System.out.println ("Compilation failed");
}
try {
fileManager.close ();
} catch (IOException e) {
}
}
}
Its from [Original Article: Java2S: Java Compiler tools: how you can compile a Java source from inside a Java program|http://www.java2s.com/Code/Java/JDK-6/JavaCompilertoolshowyoucancompileaJavasourcefrominsideaJavaprogram.htm]
I made a few changes to it to accomodate for some errors. But can someone explain to me what is going on in this piece of code.
Just to make it clear, I do not own this code/ it is not mine and will take it out of this forum if required to do so.
Hopefully you all can help me out with this.