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".

import java.io.*;

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"    
                         + "   }}";

         createClass(code,"C.java");
         Class classB = Class.forName("C");
         Base b = (Base)classB.newInstance();         
         b.run();
  }

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








No comments:

Post a Comment