Java static proxy and dynamic proxy
•
Java
proxy pattern
Static proxy
According to the standard implementation method of agent mode:
public interface API {
public void method();
}
public static class APIImpl implements API {
@Override
public void method() {
System.out.println("do work...");
}
}
public static class ProxyAPI implements API {
API api;
public ProxyAPI(API api){
this.api = api;
}
@Override
public void method() {
System.out.println("proxy start");
this.api.method();
System.out.println("proxy end");
}
}
The characteristic of static proxy is that the proxy class implements the API interface by itself, but each method call is in the incoming API object. If there are many interface methods, or there are multiple interfaces that need agents, the workload of static agents will be relatively large and will be poorly evaluated.
Dynamic agent
Proxy class:
public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h) throws IllegalArgumentException
Parameter Description:
realization
public static class APIProxy {
public static <T> T proxy(final T target) {
return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new InvocationHandler() {
@Override
public Object invoke(Object proxy,Method method,Object[] args) throws Throwable {
Object result = null;
System.out.println("proxy start");
//执行方法
result = method.invoke(target,args);
System.out.println("proxy end");
return result;
}
});
}
Cglib dynamic proxy
Implementation method:
public static class cglibProxy implements MethodInterceptor {
private Object target;
static cglibProxy _instance = new cglibProxy();
/**
* 创建代理对象
*
* @param target
* @return
*/
public static <T> T proxy(final T target) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());
// 回调方法
enhancer.setCallback(_instance);
// 创建代理对象
return (T) enhancer.create();
}
@Override
public Object intercept(Object obj,Object[] objects,MethodProxy methodProxy) throws Throwable {
System.out.println("proxy start");
Object result = methodProxy.invokeSuper(obj,objects);
System.out.println("proxy end");
return result;
}
}
For the principle of cglib, see cglib dynamic agent
test
public static void main(String[] args) {
API api = new APIImpl();
// 静态代理
API proxyApi = new ProxyAPI(api);
proxyApi.method();
// jdk proxy
API proxyApi2 = APIProxy.proxy(api);
proxyApi2.method();
// cglib
API proxyApi3 = cglibProxy.proxy(api);
proxyApi3.method();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码