4 Replies Latest reply on Feb 21, 2008 3:21 PM by Guy Korland

    Duplicate a method

    Guy Korland Newbie

      Hi,

      I'm trying to duplicate a method, what is the a best practice?
      e.g.

      public void foo(){
      some code...
      }

      add another duplicate method:

      public void foo(int i){
      some code...
      }

        • 1. Re: Duplicate a method
          Luca Ferrari Newbie

          You are not trying to duplicate, rather to overload the method. I usually do this:
          1) create a StringBuffer where I place the java source code for the new method;
          2) use CtNewMethod.make() to obtain a new CtMethod for the source code;
          3) add the method to the CtClass.

          • 2. Re: Duplicate a method
            Guy Korland Newbie

            The thing is that I want the new method to look the same as the original code, for that I want to copy the original code.

            The problem is that when I use the:
            newMethod.setBody(method, null); to copy the original body I need to add the following code to fix the MaxLocals:
            CodeAttribute code = newMethod.getMethodInfo().getCodeAttribute();
            code.setMaxLocals(code.getMaxLocals() + 1);

            Isn't there a better way?

            Guy

            • 3. Re: Duplicate a method
              Shigeru Chiba Expert

              Your way is dangerous. Suppose the following method:

              int foo(int i) {
              int j = 3;
              return j + i;
              }

              At the bytecode level, the variable i would be register 1 and j would be register 2.

              If you add a parameter k, you must change the bytecode
              of the method body so that the variable j will be register
              3 because k will be register 2.

              Current Javassist does not provide direct support for
              adding a new parameter. :-<


              • 4. Re: Duplicate a method
                Guy Korland Newbie

                Yes, thanks I found it myself few days ago, do you think there's a way to make it happen anyway?