0 Replies Latest reply on Jun 6, 2010 8:07 PM by nagure

    Generating a main method

      Hi there, folks. Sorry if this is a dumb question, but I couldn't find any good explanation so far.

       

      I have the following code, a plain and simple HelloWorld:

       

      ClassPool pool = ClassPool.getDefault();
      CtClass cc = pool.makeClass("HelloWorld");
      CtMethod mt = CtNewMethod.make("public static void main(String[] args) { System.out.println(\"Hello World!\"); }", cc);
      cc.addMethod(mt);
      cc.writeFile();
      

       

      As you see, there's a main method in this new generated class. So far, so good. It works like a charm.

       

      I'd like to create this very same method using the other way:

       

      CtClass cc = pool.makeClass("HelloWorld");
      CtMethod m = new CtMethod(CtClass.voidType, "main", new CtClass[] { } , cc);
      m.setModifiers(Modifier.PUBLIC & Modifier.STATIC);
      cc.addMethod(m);
      m.setBody("{ System.out.println(\"Hello World!\"); }");
      cc.setModifiers(cc.getModifiers() & ~Modifier.ABSTRACT);
      cc.writeFile();
      

       

      Unfortunately, this code fails. I couldn't figure out how I'm supposed to handle String args[] with CtClass.TYPE, as it seems there are only primitive types.

       

      Thanks a lot!