Friday, June 1, 2012

Compiling Java Source File From Running Java Application

Hi All,

id you know that you can compile Java source code from your running Java Application? It’s not even so hard and the JavaCompiler javadoc is quite verbose.
Try it for yourself:


package com.piotrnowicki.javacompiler; 

 

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider; 

public class Executor {
    public static void main(String[] args) {
        JavaCompiler jcp = ToolProvider.getSystemJavaCompiler(); 

        // Compile pointed *.java file
        jcp.run(null, null, null, "/home/piotr/MyClass.java");
    }
}
Now imagine that you can compile your Java code from a Java application that compiles your Java code. Why…? Because we can and because it’s so inception!

No comments: