Compiling a Java class using JavaCompiler
19 April 2008Java 6 introduces a way to compile Java classes from a Java class. In this post, I will present an example to show how this is done.
I have a Test.java file:
public class Test{ public static void main(String[] args) { // TODO code application logic here System.out.println("Hello World"); callMe(); } public static void callMe(){ System.out.println("Hello Babar dost"); } }
I want to compile it from my Java class. This is possible in Java 6 using javax.tools package. Lets see how this is done:
import javax.tools.*; import java.io.*; import java.util.Arrays; public class Main { public static void main(String[] args) { File file = new File("C:\\Test.java"); File files1 = file ; // input for first compilation task JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files1)); compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call(); } }
I compiled Main.Java and executed it. After execution, I could see Test.class in the c drive which means that Test.java was compiled successfully.
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: Compiling a Java class using JavaCompiler