创建被代理类
package javaassist;
public class Hello {
public void say() {
System.out.println("Hello");
}
}
创建MethodHandler
package javaassist;
import java.lang.reflect.Method;
import javassist.util.proxy.MethodHandler;
public class MethondAop implements MethodHandler {
@Override
public Object invoke(Object arg0, Method arg1, Method arg2, Object[] arg3)
throws Throwable {
System.out.println("我来自代理");
return arg2.invoke(arg0, arg3);
}
}
创建测试类
package javaassist;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import model.User;
import annotation.Column;
import annotation.Table;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;
public class Test {
public static void main(String[] args) throws Exception {
ProxyFactory proxyFactory=new ProxyFactory();
proxyFactory.setSuperclass(Hello.class);
Class<?> classes=proxyFactory.createClass();
MethondAop methondAop=new MethondAop();
Object ret=classes.newInstance();
((ProxyObject)ret).setHandler(methondAop);
((Hello)ret).say();
}
}
运行结果
我来自代理
Hello
PS
ProxyFactory 的方法 public void setHandler(MethodHandler mi) ,已经过期,api给出的理由如下
Deprecated. since 3.12 use of this method is incompatible with proxy class caching. instead clients should call method ProxyObject.setHandler(MethodHandler) to set the handler for each newly created proxy instance. calling this method will automatically disable caching of classes created by the proxy factory. Sets the default invocation handler. This invocation handler is shared among all the instances of a proxy class unless another is explicitly specified.