Java Compiler API (brief intro)
by, 11-28-2011 at 07:49 PM (1458 Views)
We all know that javac command is used to compile the java classes. Even if we are using some IDE (Eclipse, JBuilder, NetBeans), javac is called at the background for compilation. But with the release of Java 6, it has become possible to compile Java class from a Java class.
The classes related to Java compiler are packed into javax.tools package.
There is a class called ToolProvider (javax.tools) whose getSystemJavaCompiler() method returns an instance of some class that implements the JavaCompiler interface. Now we can use this compiler instance to create a compilation task that will perform the actual compilation. We have to provide the classes to be compiled to the compilation task. The compiler API provides a file manager abstraction called JavaFileManager for this. The JavaFileManager is used to allow Java files to be retrieved from various sources.
Lets review the code snippet:
Java Code://Get an instance of java compiler JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); //Get a new instance of the standard file manager implementation StandardJavaFileManager fileManager = compiler. getStandardFileManager(null, null, null); // Get the list of java file objects, in this case we have only // one file, TestClass.java Iterable compilationUnits1 = fileManager.getJavaFileObjectsFromFiles("TestClass.java");