1 Reply Latest reply on Jul 31, 2003 11:38 AM by chiba

    redefining a method in a subclass with setbody

    pouparte

      hi all,

      first, congratulations for you shigeru and the other authors for this very nice and powerful product called javassist.

      second, i'd like to mention something that take some time to resolve :

      i wanted to redefine a method foo() in a class B subclass of A.

      class A {
      public void foo() {};
      }

      the first solution i used was :

      CtClass a = ...
      CtClass b = pool.makeClass("B",a);
      CtMethod m = b.getMethod("foo",...);
      m.setBody("...");

      but it had no effect on b.foo(), it's always a.foo() which is used.

      so i tried :

      CtClass b = pool.makeClass("B",a);
      CtMethod m = a.getMethod("foo",...);
      CtMethod m2 = CtNewMethod.copy(m,b,null);
      m2.setBody("...");
      b.addMethod(m2);

      but it failed in error saying that it's impossible to add foo().

      finally, i succeeded using this way :

      CtClass b = pool.makeClass("B");
      CtMethod m = a.getMethod("foo",...);
      CtMethod m2 = CtNewMethod.copy(m,b,null);
      m2.setBody("...");
      b.addMethod(m2);
      b.setSuperClass(a);

      ********************************

      it would be very nice if somebody could give his feeling on this.

      regards,

      erwann.

        • 1. Re: redefining a method in a subclass with setbody
          chiba

          Hi,

          That's a specification. To avoid such confusion,
          I added the following text to the tutorial.

          - Chiba

          Methods are represented by CtMethod objects. CtMethod provides several methods for modifying the definition of the method. Note that if a method is inherited from a super class, then the same CtMethod object that represents the inherited method represents the method declared in that super class. A CtMethod object corresponds to every method declaration.

          For example, if class Point declares method move() and a subclass ColorPoint of Point does not override move(), the two move() methods declared in Point and inherited in ColorPoint are represented by the identical CtMethod object. If the method definition represented by this CtMethod object is modified, the modification is reflected on both the methods. If you want to modify only the move() method in ColorPoint, you first have to add to ColorPoint a copy of the CtMethod object representing move() in Point. A copy of the the CtMethod object can be obtained by CtNewMethod.copy().