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

    Modify static block

    ikestrel

      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
          yamazaki

          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
            chiba

            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.