public interface IService{
Object execute(Object... args);
}
public class ServiceImpl implements IService{
private Object execute(Object... args){
// do execute
}
}
// 静态代理
public class ProxyService implements IService{
private final ServiceImple serviceImpl;
public ProxyService(ServiceImpl serviceImpl){
this. serviceImpl = serviceImpl;
}
public void execute(){
// do before
Object result = serviceImpl.execute();
// do after
return result;
}
}
// 动态代理
public class JdkDynamicProxy{
public static void main(String[] args){
SerivceImpl target = new ServiceImpl();
Object proxy = Proxy.newProxyInstance(Thread.currentThread().getClassLoader(), new Class[]{IService.class}, new InvacationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args){
// do before
Object result = method.invoke(target, args);
// do after
return result;
}
})
IService iService = (IService) proxy;
// 即($ProxyN extends Proxy implements IService)#execute(...)
Object result = iService.execute(...);
}
}
// Java Proxy API 关注部分代码
public class Proxy{
private InvocationHandler h;
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h){
...
}
}
// 由于 Java 是单继承多实现的,因此 JDK 动态代理必须是基于接口的,这也是 Spring AOP 基于接口的 AOP 是使用 JDKDynamicAopProxy,而基于类
// 的 AOP 是使用 CglibAopProxy 的原因
public class $ProxyN extends Proxy implements IService{
public Object execute(Object... args){
// 因此在 InvocationHandler.invoke(Object,Mehtod,Object[]) 中 method.invoke(Object,Object[])不能使用代理后对象进行反射调用, 否则会死循环
return this.h.invoke(this, m3,args);
}
// 忽略 Object 方法
static{
m3 = Class.forName("xxx.xxx.IService").getMethod("execute", new Class[0]);
// 忽略 Object 方法
}
}
查看生成代理类文件 vm options参数设置
- jdk8及以前用 -Dsun.misc.ProxyGenerator.saveGeneratedFiles=true
- jdk8以后 用 -Djdk.proxy.ProxyGenerator.saveGeneratedFiles=true