文章目录
JDK动态代理ProxyInvocationHandler调用
CGLIBProxyInterceptor调用
JDK动态代理
通过多态调用,需要有接口
ProxyInvocationHandler
@AllArgsConstructor
public class ProxyInvocationHandler implements InvocationHandler {
private ServerInterface serverInterface
;
@Override
public Object
invoke(Object proxy
, Method method
, Object
[] args
) throws Throwable
{
method
.invoke(serverInterface
,args
);
return null
;
}
}
调用
public void function() {
ServerInterface server
= (ServerInterface
) Proxy
.newProxyInstance(
getClass().getClassLoader(),
new Class[]{ServerInterface
.class},
new ProxyInvocationHandler(new ServerImpl()));
server
.function();
}
CGLIB
ProxyInterceptor
public class ProxyInterceptor implements MethodInterceptor {
@Override
public Object
intercept(Object o
, Method method
, Object
[] objects
, MethodProxy methodProxy
) throws Throwable
{
methodProxy
.invokeSuper(o
,objects
);
return null
;
}
}
调用
public void function() {
Enhancer enhancer
= new Enhancer();
enhancer
.setSuperclass(Server
.class);
enhancer
.setCallback(new ProxyInterceptor());
Server server
= (Server
) enhancer
.create();
server
.function();
}