2 Replies Latest reply on Jun 4, 2005 3:33 PM by daniel nguyen thanh son

    altering constructor implementation: how-to ?

    daniel nguyen thanh son Newbie

      I'm new to the javassist library.
      I need to change a constructor's implementation that throws an exception.

      I'm accessing the CodeAttribute and CodeIterator to alter the implementation as follows:

      However, if i access the class after using the specified constructor, it still throws exception.
      If displaying the content of the byte-code after the modification (ie: line 7), the athrow is replaced with the POP instruction.
      However, after, when reusing the classpool, ctclass and methodinfo to check at the constructor, the code remains unchanged.

      I've been trying to figure it out for a while now.
      Any help would be greatly appreciated.


      I use the api the following way:
      1- ClassPool cp = ClassPool.getDefault ();
      2- ClassLoader loader = PdfErrorTest.class.getClassLoader ();
      3- cp.insertClassPath (new javassist.LoaderClassPath (loader));
      4- CtClass ctclazz = cp.get (TEST_CLASS);
      5- MethodInfo mi = getTheConstructor (ctclazz, "(Ljava/lang/String;)V");
      6- if (needToFix (mi))
      7- {
      8- // Get opCode index to change...
      ...
      9- CodeAttribute codeAttribute = mi.getCodeAttribute ();
      10- CodeIterator iterator = codeAttribute.iterator();
      11- iterator.writeByte (POP, thrownIndex);
      // Just commit the changes then
      12- byte[] b = ctclazz.toBytecode();
      13- Class cl = Class.forName("java.lang.ClassLoader");
      14- java.lang.reflect.Method defineClassMethod =
      15- cl.getDeclaredMethod("defineClass", new Class[] {
      16- String.class,
      17- byte[].class, int.class, int.class });
      18- defineClassMethod.setAccessible (true);
      19- Object[] args = new Object[] {
      20- ctclazz.getName(),
      21- b,
      22- new Integer (0), new Integer (b.length)};
      23- defineClassMethod.invoke (targetedLoader, args);
      24- defineClassMethod.setAccessible(false);
      25-}