1 Reply Latest reply on Apr 23, 2008 8:16 AM by Michael Parkin

    Best Practice for 'Wrapping' a Method

    Michael Parkin Newbie

      Hi,

      Sorry if this question has been answered in another thread - please point me to the relevent answer if this has already been answered.

      In Section 4 of the java assist tutorial it gives an example where a method is 'wapped'in another method, i.e.:

      void move(int newX, int newY) { x = newX; y = newY; }
      
      void move(int newX, int newY, int newZ) {
       // do what you want with newZ.
       move(newX, newY);
      }


      What is the best practice to do add the second method to a class in Javassist given bytecode containing the first method?

      Many thanks,

      Michael.

        • 1. Re: Best Practice for 'Wrapping' a Method
          Michael Parkin Newbie

          So here's what I'm doing to achieve the above. Assume that m is the original CtMethod, c is the class it's declared in, pool is a ClassPool and that we're adding a new parameter of type String.

          // Add a new parameter of type string to the list of parameters
          CtClass[] parameters = m.getParameterTypes();
          CtClass[] newParameters = new CtClass[parameters.length + 1];
          System.arraycopy(parameters, 0, newParameters, 0, parameters.length);
          newParameters[parameters.length] = pool.get("java.lang.String");
          
          // Create and configure method
          CtClass returnType = m.getReturnType();
          CtMethod newM = new CtMethod(returnType, m.getName(), newParameters, c);
          newM.setExceptionTypes(m.getExceptionTypes());
          newM.setModifiers(m.getModifiers());
          
          // Add and configure method body
          newM.setBody(m, null);
          newM.insertBefore("// string parameter is $args[$args.length-1]");
          
          // Add new method to class
          c.addMethod(newM);
          


          Is this the best way to do this?

          Thanks,

          Michael.