Created
February 18, 2012 03:34
-
-
Save zavakid/1857221 to your computer and use it in GitHub Desktop.
javaassist insert some code before method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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