Java Compiler API (brief intro)
21 April 2008We 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 classs from a Java class.
The classes related to Java compilier 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:
//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<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles("TestClass.java");
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Java Compiler API (brief intro)