jdk动态代理
- 定义接口,被代理对象要实现接口
- 实现InvocationHandler
- 调用Proxy.newProxyInstance生成代理对象
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class InvocationHandlerImpl implements InvocationHandler {
private Object subject;
public InvocationHandlerImpl(Object subject) {
this.subject = subject;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("前置通知");
Object retVal = method.invoke(subject, args);
System.out.println("后置通知");
return retVal;
}
public static void main(String[] args) {
Subject target = new RealSubject();
ClassLoader classLoader = target.getClass().getClassLoader();
Class<?>[] interfaces = target.getClass().getInterfaces();
InvocationHandlerImpl invocationHandler = new InvocationHandlerImpl(target);
Subject proxyInstance = (Subject) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
proxyInstance.sayHello("阿百川");
}
}
interface Subject {
public void sayHello(String name);
public void sayGoodbye(String name);
}
class RealSubject implements Subject {
public void sayHello(String name) {
System.out.println("hello " + name);
}
public void sayGoodbye(String name) {
System.out.println(name + " good bye !");
}
}
cglib代理
- 自定义MethodInterceptor
- 通过Enhancer创建代理
package proxy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
class HelloService {
public HelloService() {
System.out.println("HelloService构造器");
}
final public String sayOthers(String name) {
System.out.println("HelloService:sayOthers -> " + name);
return null;
}
public void sayHello() {
System.out.println("HelloService:sayHello");
}
}
public class MyMethodInterceptor implements MethodInterceptor {
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("前置通知");
Object retVal = methodProxy.invokeSuper(proxy, args);
System.out.println("后置通知");
return retVal;
}
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(HelloService.class);
enhancer.setCallback(new MyMethodInterceptor());
HelloService helloService = (HelloService) enhancer.create();
helloService.sayHello();
}
}