javassist使用实例

import java.io.IOException;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;


public class Test1 {
static {
try {
ClassPool pool = ClassPool.getDefault();
CtClass clazz = pool.get("Hello");
CtMethod method = clazz.getDeclaredMethod("sayHello");
method.insertBefore("{ System.out.println(\"方法调用前\"); }");
method.insertAfter("{ System.out.println(\"方法调用后\"); }");
clazz.writeFile();
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CannotCompileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Hello hello = (Hello) ClassPool.getDefault().get("Hello").toClass().newInstance();
hello.sayHello();
}
}

你可能感兴趣的:(javassist)