Skip to content

Instantly share code, notes, and snippets.

@zavakid
Created February 18, 2012 03:34
Show Gist options
  • Save zavakid/1857221 to your computer and use it in GitHub Desktop.
Save zavakid/1857221 to your computer and use it in GitHub Desktop.
javaassist insert some code before method
package com.zavakid.javassist.test;
public class Hello {
public void say(){
System.out.println("Hello world.");
}
}
//======================
package com.zavakid.javassist.test;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
public class Test {
public static void main(String[] args) throws Exception {
ClassPool classPool = ClassPool.getDefault();
CtClass clazz = classPool.get("com.zavakid.javassist.test.Hello");
CtMethod method = clazz.getDeclaredMethod("say");
method.insertBefore("{System.out.println(\"Hello.say()\");}");
Hello newH = new Hello(); // this will load the original Hello.class
newH.say();
Class c = clazz.toClass();
Hello h = (Hello) c.newInstance(); // this will throw LinkError
h.say();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment