Java SE 6 Compiler API

Now that Java SE is released I wanted to cover one of my favorite feature, the Compiler API. I already wrote about a cool hack that can be done in previous versions of the JDK to compile Java code at runtime. I also wrote about compiling Groovy at runtime. Now I will cover how to compile Java code using the new Compiler API introduced in the JDK SE 6. Please not that the following code use classes that are currently only available with the JDK, not the JRE.

To get started you will need to instantiate a Java Compiler and Java File Manger.

JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);

The next step is to create a compilation task to the Java Compiler. You can add as many task to the Java compiler as you may need. Also note that the getJavaFileObjects method accepts a variable number of arguments so you could pass in as many files as you may need. Also, don’t forget to close the Java File Manager when you are done with it.

File javaFile = new File(“c:/src/com/juixe/Entity.java”);
// getJavaFileObjects’ param is a vararg
Iterable fileObjects = sjfm.getJavaFileObjects(javaFile);
jc.getTask(null, sjfm, null, null, null, fileObjects).call();
// Add more compilation tasks
sjfm.close();

At this point with the above code, if there are no errors the class files would compile to c:/src. If you want to output the class files in a different location you can add options to the compilation task with code similar to the following.

String[] options = new String[]{“-d”, “c:/bin”};
jc.getTask(null, sjfm, null, Arrays.asList(options), null, fileObjects).call();

Once you have compiled the Java source file using the new Java Compiler API, you may want to load the class into your running system. To load a Java class compiled using the Compiler API you can use code similar to that used to load a class compiled using embedded Groovy. Here is how you can load a newly compiled class at runtime.

File outputDir = new File(“c:/bin”);
URL[] urls = new URL[]{outputDir.toURL()};
URLClassLoader ucl = new URLClassLoader(urls, cl);
Class clazz = ucl.loadClass(“com.juixe.Entity”);

Technorati Tags: , , , , , , , , ,

Related posts:

  1. Java SE 6 Released
  2. The Java 3D API and Java Binding for OpenGL
  3. Migrating to Java 6
  4. Java Persistence API – Best Practices and Tips
  5. Invoke Javac At Runtime
  6. API Design


5 Responses to “Java SE 6 Compiler API”

Leave a Reply