2. Create a JavaFileObject instance for each of the compilation unit.
a) If the source is not from file system, then we need to write a class implementing fromJavaFileObject interface. Java 6 provides a sample implementation of this in the form of SimpleJavaFileObject. We can extend from this and customize it as per our needs.
out: is a writer object, if not null, this would be used to write all the compilation errors. If null, the errors are written to the standard error console, i.e., System.err.
fileManager: is an instance of the JavaFileManager, which abstracts programming language source and class files. In this context, file means an abstraction of regular files and other sources of data.
diagnosticListener: which acts as a listener to the compilation events happening and logs any issues found. The DiagnosticCollector, we have created here is impleting this listener and that stores all the compilation diagnostic messages. If this is not passed, the compilation issues will be logged on standard error console.
options: the compilation options to be passed during compilation, this can be null if there are no options to be used.
classes: class names (for annotation processing), null means no class names
compilationUnits: these are the list of JavaFileObject instances, that need to be compiled.
9. Finally, call the method ‘call’ on compilation task, which does the actual job, and returns ‘true’ on success or ‘false’ otherwise.
that’s it. We are pretty much done with the example. The piece of code mentioned over here doesn’t result into any errors. Introduce some error into the code string and play with it. By the way, after successful compilation the class file would be generated under the current folder if you don’t pass in the java options I mentioned over here. If you are passing the same java options I mentioned here, make sure you create a folder by the name ‘bin’ under your current folder. Otherwise this will result into an error.
Who will benefit from this feature?
Application server developers: Application server need to generate java files from JSP code and compile them dynamically, thus reducing the application hot deployment time.
IDEs and Developer Tools like Ant: This API helps them to load the compiler once and perform compilation as and when needed instead of loading an external compiler each time the code changes.
Here is the full-version of the example source code.