2 Replies Latest reply on Oct 25, 2004 3:47 AM by gpanneerpandi

    is it possible to create .class file using a String

    gpanneerpandi

      Dear Experts,
      THe following class Test3 writing a "HelloWorld.class" file for the following program using javassist, without
      having a HelloWorld.java file.

      import java.io.*;
      import javassist.*;
      /*
      This program gnerates "HelloWorld.class " for the following java code
      public class HelloWorld{
      int abc;
      public HelloWorld(){
      abc=100;
      }
      public static void main(String a[]){
      HelloWorld h=new HelloWorld();
      System.out.println(h.abc);
      }
      }
      */

      public class Test3 {
      public static void main(String[] args) throws Exception {
      ClassPool pool = ClassPool.getDefault();
      CtClass cc = pool.makeClass("HelloWorld");
      CtField sf= CtField.make("int abc;",cc);
      cc.addField(sf);
      String str="public HelloWorld(){abc=100;}";
      CtConstructor ccon=CtNewConstructor.make(str,cc);
      cc.addConstructor(ccon);
      CtMethod m = CtNewMethod.make(
      "public static void main(String a[]){" +
      "HelloWorld h=new HelloWorld();"+
      "System.out.println(h.abc);" +
      "}", cc);
      cc.addMethod(m);
      cc. writeFile();

      }
      }

      ==================================
      My doubts are:
      1.In the above method , we are adding fields,constructor,methods seperatley
      by
      CtClass cc = pool.makeClass("HelloWorld");
      cc.addField(sf);
      cc.addMethod(m);

      2.my doubt is insted of adding each element(class,filed,constructor,method...) seperatly
      is the following is possible in javassist

      String str= "import java.io.*;"+
      " public class HelloWorld{"+
      "int abc;"+
      " public HelloWorld(){"+
      "abc=100;"+
      "}"+
      "public static void main(String a[]){"+
      "HelloWorld h=new HelloWorld();"+
      " System.out.println(h.abc);"+
      "}"+
      "}";
      is it possible to create a "HelloWorld.class" using javassist by having the above String as a parameter

      3.When we are generateing class on the fly(like in the above example),how to include packages

      Thanks in Advance
      Jai Bharat Matha
      G.Panneer Pandi
      India