java study notes (Intermediate articles) -JDK dynamic proxies

First, what is a proxy mode

I believe we all know the concept of agents in the business, the agents everywhere. Suppose you want to buy something, you can not go buy a real factory, it is impossible to put forward demands directly with manufacturers, agents is the middle of a bridge connecting buyers and manufacturers. What are you looking for or customized products, styles and price specifications of what needs to communicate directly with agencies like the communication by the agents with real companies, so buyers have any questions can consult our distributors, manufacturers also can concentrate on the real do product, do not control other things, the buyers can not intervene in manufacturers thing.

In the above relationship, the manufacturer is to be a proxy object, the agent is a proxy object, and the buyer is the caller. There are several java dynamic proxy technologies, including JDK, CGLIB, Javassist, etc., and here I will take CGLIB with JDK dynamic proxy for comparison.

Second, the significance

Dynamic proxy meaning is generated with a placeholder (proxy object), the real object to the agent, so as to achieve the purpose of controlling real objects. To understand the dynamics of agency, we must first have knowledge of reflection.

Third, to achieve dynamic agent of step

Agent implementation is divided into two main steps:

1. Establish agency relationship proxy object and real object

2. The method of logic implemented in the proxy object

Four, JDK dynamic proxies

JDK dynamic proxy, JDK comes with features, in java.lang.reflect. * Package. To achieve JDk dynamic proxy, the proxy must be generated via the interface to the object.

1. First define a simple interface HelloWorld.java

public interface HelloWorld {
    void sayHello();
}

2.HelloWorld implementation class HelloWorldImpl.java

public class HelloWorldImpl implements HelloWorld {
    @Override
    public void sayHello() {
        System.out.println("hello world");
    }
}

3. Establish agency relationship, we must implement the interface InvocationHandler. It is the only interface to invoke the method needs to be implemented, which proxy logic implemented when the proxy object scheduling method, will be mapped to invoke methods, actually achieved by reflection. And bind () method is an agency relationship to create a proxy object newProxyInstance Proxy, the classloader first argument, the second argument hanging interfaces, the third parameter is the realization of a proxy logic invoke class method .

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxy implements InvocationHandler {
    //真实对象
    private Object target = null;

    /**
     * 建立真实对象与代理对象之间的关系
     * @param target 传入真实对象
     * @return
     */
    public Object bind(Object target){
        this.target = target;
        return Proxy.newProxyInstance
            (target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),this);
    }

    /**
     *  代理逻辑
     * @param proxy 代理对象
     * @param method 当前调度的方法
     * @param args 调度方法的参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("进入代理逻辑方法");
        System.out.println("在调用真实对象之前的服务");
        Object object = method.invoke(target,args);
        System.out.println("在调用真实对象之后的服务");
        return object;
    }
}

4. Test

import org.junit.Test;

public class JdkProxyTest {

    @Test
    public void test_JdkProxy(){
        JdkProxy proxy = new JdkProxy();
        HelloWorld helloWorld = null;
        try {
            helloWorld = (HelloWorld) proxy
                .bind(Class.forName
            ("com.xcl.ssm.chapter2.jdkproxy.HelloWorldImpl")
                            .newInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }
        helloWorld.sayHello();
    }
}

Five, CGLIB dynamic proxies

It says JDK dynamic proxy must be achieved by means of the interface can be achieved, while CGLIB is not just to have a non-abstract class can be. Our top HelloWorldImpl class, for example, there is no interface to a HelloWorld. JDK invocationHandler dynamic proxy must implement an interface, it must be achieved MethodInterceptor CGLIB-interfaces, a method which only needs to be implemented Intercept (), which need to achieve the proxy logic. I remember oh lead pack before writing code, which is provided by a third-party technology.


public class CglibProxy implements MethodInterceptor {

    /**
     *  生成CGLIB代理对象
     * @return
     */
    public Object getProxy(Class clz){
        //CGLIB增强类对象
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clz);
        //设置当前对象为代理逻辑对象
        enhancer.setCallback(this);
        //生成并返回代理对象
        return enhancer.create();
    }

    /**
     *  代理逻辑方法
     * @param proxy 代理对象
     * @param method 方法
     * @param args 参数
     * @param methodProxy 方法代理
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("调用真实对象前");
        //通过反射调用真实对象的方法
        Object obj = methodProxy.invokeSuper(proxy,args);
        System.out.println("调用真实对象后");
        return obj;
    }
}

VI Summary

To fathom the true dynamic proxy to be very familiar with the reflection mechanism, can be seen from the above code, or underlying implementation of dynamic proxies based on reflection, we know that reflection is very consumption performance, which brings some performance issues, but in order to easy on the development of this sacrifice is worth it. Framework we learn, such as spring, mybatis, have extensive use of dynamic proxy technology, are interested in children's shoes can go read the source code (not a representation I've seen a lot of source code), there is used a lot of design patterns to improve their the code level is helpful. Well, stop here ~

Like my little friends remember scan concern Yo ~

Guess you like

Origin www.cnblogs.com/chlinlearn/p/11360205.html