0 Replies Latest reply on Oct 30, 2009 8:19 PM by Igor Polevoy

    Javassist can't seem to instrument static method

    Igor Polevoy Newbie

      I stumbled upon a Javassist problem, when it fails to add code with insertBefore().

      If someone can help, I would really appreciate this.


      package test;
      public class TheAddress extends TheModel {
       static{
       foo("The address!!!");
       }
      }
      


      package test;
      public class TheModel {
       public static void foo(String param){
       System.out.println("Inside foo, param: " + param);
       }
      }


      package test;
      import javassist.*;
      public class JavassistTest {
      
       public static void main(String[] args) throws Exception {
      
       ClassPool pool = ClassPool.getDefault();
       CtClass clazz = pool.get("test.TheAddress");
       CtMethod foo = getMethod("foo", clazz);
      
       foo.insertBefore("{ System.out.println(\"inserted before foo!\");}");
      
       clazz.writeFile();
       clazz.toClass().newInstance();
       }
      
       static CtMethod getMethod(String name, CtClass target){
       for (CtMethod method : target.getMethods()) {
       if (name.equals(method.getName())) return method;
       }
       return null;
       }
      }


      cheers!