Learn reflex with teacher Wang (11): Dynamic agent

Source: Internet
Author: User

Learn reflex with teacher Wang (11): Dynamic agent Teacher: Wang Shaohua QQ Group: 483773664 Learning Content

Learn to use dynamic proxies


First, dynamic agent

Dynamic proxy: Dynamic proxies are more flexible than static proxies implemented in the previous section because they do not have to specify a proxy class to proxy the proxy object when we design the implementation, and we can defer this designation until the program is run by the JVM.

Dynamic proxies is a feature introduced in Java 1.3, A proxy class and a Invocationhandler interface are provided under the Java Java.lang.reflect package to generate a JDK dynamic proxy object from this class and interface.

Second, proxy and Invocationhandler (a) proxy
1 Introduction

Proxy provides a static method for creating dynamic proxy and proxy objects, which is also the parent class for all dynamic proxies. If we dynamically generate implementation classes for one or more interfaces in a program, you can use proxies to create dynamic proxy classes, or you can use proxies to create dynamic proxy implementations if you need to dynamically create implementations for one or more interfaces.

2 Proxy provides the following two methods for creating dynamic proxy classes and dynamic proxy instances

public static class<?> Getproxyclass (ClassLoader loader, class<?> .... Interfaces): Create a Class object corresponding to the dynamic proxy classes, The proxy class implements the multiple interfaces specified by the interfaces. The first classloader specifies the class loader that generates the dynamic proxy class.

public static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h) : Create a dynamic proxy object directly, the implementation class of the proxy object implements the series interface specified by interfaces, and the Invoke method that executes the Invocationhandler object is substituted for each method of executing the proxy object.

(ii) Invocationhandler

The Invocationhandler interface is an implementation interface of the proxy handler class that acts as the public parent class of the calling processor for the proxy instance, and each instance of the proxy class can provide a related specific invocation handler (subclass of the Invocationhandler interface)

There is a method in the Invocationhandler interface

1 Object invoke(Object proxy,Method method, Object[] args)

Parameters:

Proxy-the object being proxied

Method-Methods to invoke

Args-the parameter that is required when the method is called, or null if the interface method does not use a parameter. The parameters of the base type are wrapped in an instance of the appropriate basic wrapper class (such as Java.lang.Integer or Java.lang.Boolean).

Return:

The value returned from the method call of the proxy instance. If the declaration return type of an interface method is a base type, the value returned by this method must be an instance of the corresponding base wrapper object class, otherwise it must be a type that can be assigned to the declaration return type. If the value returned by this method is null and the return type of the interface method is the base type, the method call on the proxy instance throws NullPointerException. Otherwise, if the value returned by this method is incompatible with the declared return type of the interface method described above, the method call on the proxy instance throws classcastexception.

The realization of dynamic Agent (I.) the implementation of dynamic agent
1. Implement the Invocationhandler interface to create your own calling processor
12345678910111213141516171819202122232425262728 public class DynmicProxy implements InvocationHandler{    private Object targetObject;    public DynmicProxy(){}    publicDynmicProxy(Object targetObject) {        this.targetObject = targetObject;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args)            throws Throwable {        preHandle();        Object ret = method.invoke(targetObject, args);        postHandle();        return ret;    }    /**     * 代理类特有的方法     */    private void preHandle(){        System.out.println("preHandle");    }    /**     * 代理类特有的方法     */    private void postHandle(){        System.out.println("postHandle");    }}
2. Create a dynamic proxy class by providing an array of ClassLoader and proxy interface types to the proxy class
1234567 // 目标对象        UserService userService = new UserServiceImpl();        // 创建代理类        UserService proxyUserService = (UserService) Proxy.newProxyInstance(                userService.getClass().getClassLoader(),                 userService.getClass().getInterfaces(),                 new DynmicProxy(userService));
3. Calling target object methods through proxy objects
12 //通过代理对象调用目标对象的方法        proxyUserService.save();
(ii) Code optimization
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 public class LogHandler implements InvocationHandler{    //目标对象    private Object targetObject;    /**     * 生成代理对象:就是关联到哪个接口(与具体的实现类绑定)的哪些方法将被调用时,执行invoke方法。     * @param targetObject     * @return 返回代理对象     */    public Object newProxyInstance(Object targetObject) {        this.targetObject = targetObject;        /**         * 该方法用于为指定类装载器、一组接口及调用处理器生成动态代理类实例                第一个参数指定产生代理对象的类加载器,需要将其指定为和目标对象同一个类加载器              第二个参数要实现和目标对象一样的接口,所以只需要拿到目标对象的实现接口              第三个参数表明这些被拦截的方法在被拦截时需要执行哪个InvocationHandler的invoke方法          */        return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),                     targetObject.getClass().getInterfaces(), this);    }    /**     * proxy:要代理的对象     * method:要执行的方法     * args:方法参数     */    @Override    public Object invoke(Object proxy, Method method, Object[] args)            throws Throwable {        //原对象方法调用前调用日志处理        preHandle();        //调用目标方法:ret为目标方法返回值        Object ret = method.invoke(targetObject, args);        //原对象方法调用 后调用 日志处理方法        postHandle();        return ret;    }        /**     * 代理类特有的方法     */    private void preHandle(){        System.out.println("preHandle");    }    /**     * 代理类特有的方法     */    private void postHandle(){        System.out.println("postHandle");    }}
1234567 public class DynmicTest {    public static void main(String[] args) {        LogHandler logHandler = new LogHandler();        UserService userService = (UserService) logHandler.newProxyInstance(new UserServiceImpl());        userService.save();    }}












From for notes (Wiz)

Learn reflex with teacher Wang (11): Dynamic agent

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.