2 Replies Latest reply on May 6, 2003 11:05 AM by Shigeru Chiba

    Modify static block

    Joel Shellman Newbie

      How can I modify the static block of a class and how do I add one if one doesn't exist?

      The only thing I could find that looked related was getClassInitializer() but that always returns null.

      Thanks!

      -joel

        • 1. Re: Modify static block
          Susumu YAMAZAKI Newbie

          This answer is very tricky. I hope getClassInitializer() doesn't returns null but returns an empty CtConstructor.

          ClassPool pool = ClassPool.getDefault();
          CtClass clazz = pool.makeClass("A");
          CtField field = new CtField(CtClass.intType, "dummy", clazz);
          field.setModifiers(field.getModifiers() | Modifier.STATIC);
          clazz.addField(field, "0");
          clazz.writeFile();
          clazz.defrost();
          clazz.getClassInitializer().insertAfter("System.out.println(\"hello!\");");
          clazz.writeFile();

          • 2. Re: Modify static block
            Shigeru Chiba Expert

            getClassInitializer() should return non-null if there
            is a class initializer. I'll add a method for creating
            a new class initializer if there is not. Please wait
            for the next release, which will come soon.