1 package org.windwant.spring.core.proxy; 2 3 import javassist.ClassPool; 4 import javassist.CtClass; 5 import javassist.CtMethod; 6 7 /** 8 * Created by windwant on 2016/9/18. 9 */10 public class MyJavassistProxy {11 12 public Object getProxySelf(String clazz, String pClazz, String methodName, String methodBefore, String methodAfter){13 ClassPool cp = ClassPool.getDefault();14 CtClass ct;15 try {16 ct = cp.get(clazz);17 if(pClazz != null){18 ct.setSuperclass(cp.get(pClazz));19 }20 ct.writeFile();21 ct.defrost();22 CtMethod m = ct.getDeclaredMethod(methodName);23 if(methodBefore != null) {24 m.insertBefore(methodBefore);25 }26 if(methodAfter != null) {27 m.insertAfter(methodAfter);28 }29 Class c = ct.toClass();30 return c.newInstance();31 } catch (Exception e) {32 e.printStackTrace();33 }34 return null;35 }36 37 }
1 public void testJavassist(){ 2 String clazz = "org.windwant.spring.core.proxy.Hello"; 3 String methodBefore = "{ System.out.println(\"method before...:\"); }"; 4 String methodAfter = "{ System.out.println(\"method after...:\"); }"; 5 String pClazz = "org.windwant.spring.core.proxy.HelloP"; 6 7 Hello hello = (Hello) new MyJavassistProxy().getProxySelf(clazz, null, "say", 8 methodBefore, methodAfter); 9 hello.say();10 }