Friday, May 13, 2011

Dynamic code generation in java

Following code helps to generate a particular java class dynamically from our code.

First create an Interface called "Base" which is as follows,

public interface Base{
           public void run();


Next step is creating the implementation class of the Base interface from our code which is named as "C".


public class Invoker {

  public static void main(String[] argv) throws Exception {

         String code = "public class C implements Base {\n"
                         + "   public void run() {\n"
                         + "      System.out.println(\"I am the new class\");\n"    
                         + "   }}";

         Class classB = Class.forName("C");
         Base b = (Base)classB.newInstance();         ;

public static void createClass(String code,String file) throws Exception {
               OutputStream os =
                         new FileOutputStream(new File(file));
               Process p = Runtime.getRuntime().
               exec("javac -classpath . "+file);