Saturday, February 16, 2013

Java Compiler API

Java Compiler API has been around for a while since Java 6. We can use it to compile java files at runtime. Let's now have fun with it:

Inside main method above we have two java files to compile. Next we obtain the JavaCompiler object from ToolProvider. The JavaCompiler object then does its job to compile those files using verbose parameter supplied. Verbose parameter is useful to display compilation log. When we run the code, two .class files are created at the same location of the original files. Here is the output on console:


Let's now see another approach to compile java files.

First we state the files to compile. Then we obtain the JavaCompiler object from ToolProvider as we did before. After that we create an object of type DiagnosticCollector. This object is used to collect information during compilation process. Next, we get a StandardJavaFileManager by passing the DiagnosticCollector to the JavaCompiler's method getStandardFileManager. From the StandardJavaFileManager we create an Iterable object that contains the files being compiled. Then the actual compilation process is done by CompilationTask object by calling call() method. If an error occurs during compilation, we print the error information that has been collected by our DiagnosticCollector.

Instead of using DiagnosticCollector, we can use DiagnosticListener to collect error information. To do that we have to implement DiagnosticListener interface as shown below:

Then we can use it to compile java files as shown below:


We should be familiar with the code above since in fact we have seen it before. The only difference is that we replace the DiagnosticCollector with our own MyDiagnosticListener. Both DiagnosticCollector and MyDiagnosticListener implements DiagnosticListener interface.

So far we have seen how to compile java files reside on disk. Next we'll see how to compile java file from a string.



Again, the code above looks familiar but instead of getting the java content from files we get the java content from a string. The string itself is wrapped inside an object of type JavaObjectFromString which extends SimpleJavaFileObject which implements JavaFileObject as expected by our Iterable object.

To load the compiled class, we can use URLClassLoader by supplying it with a path where the compiled classes are put. Those classes are most likely compiled in the working directory.

0 comments:

 

©2009 Stay the Same | by TNB