Several ways of dynamic proxy

Source: Internet
Author: User
Tags aop object object throwable
The blocking capabilities of AOP are implemented by dynamic proxies in Java. To be blunt, it is to increase the slice logic on the basis of the target class, and to generate the enhanced target class (the slice logic either before the target class function executes or after the target class function executes, or when the target class function throws an exception). The different timing of the cut corresponds to different types of interceptor, such as Beforeadviseinterceptor,afteradviseinterceptor and Throwsadviseinterceptor.


So how does a dynamic proxy weave the slice logic (advise) into the target class method? Here's a detailed introduction and implementation of the two dynamic proxies used in AOP.

AOP's source code uses two kinds of dynamic agents to achieve the interception into the function: JDK dynamic proxy and cglib dynamic agent. Both methods exist at the same time, each has its advantages and disadvantages. The JDK dynamic proxy is realized by the reflection mechanism in Java, and the cglib dynamic proxy is realized by using ASM. In general, the reflection mechanism is more efficient in generating classes, and ASM is more efficient in the execution of the class after it is generated (you can solve the ASM generation class process inefficiencies by caching the ASM-generated classes). It is also important to note that the application of the JDK dynamic proxy must be the target class based on a unified interface. Without the above prerequisites, the JDK dynamic proxy cannot be applied. It can be seen that the JDK dynamic proxy has some limitations, cglib this third-party library implementation of dynamic proxy application is more extensive, and more efficient in the advantages.
1. Define interfaces and implementations

[Java] View plain copy package com.meituan.hyt.test3.service;          Public interface UserService {public String getName (int id);   Public Integer getage (int id); }


[java]  View plain  copy package com.meituan.hyt.test3.service.impl;      import& nbsp;com.meituan.hyt.test3.service.userservice;         public class  userserviceimpl implements userservice {        @Override         public string getname (int id)  {            SYSTEM.OUT.PRINTLN ("------getName------");            return  "Tom";       }           @Override        public integer getage (int  ID)  {           system.out.println ("------getage------") ;           return 10;        }  }  

2, JDK dynamic Proxy implementation

Package com.meituan.hyt.test3.jdk;  
Import Java.lang.reflect.InvocationHandler;

Import Java.lang.reflect.Method; public class Myinvocationhandler implements Invocationhandler {private Object target;//Since we're going to be agents, we have to know who we're acting for, here's O 
  
    BJ is the one who is being represented.  
    Myinvocationhandler () {super ();  
        } myinvocationhandler (Object target) {super ();  
    This.target = target;
    //Then invoke three parameters, the first parameter is the agent, if you want to do some action on the agent can use this parameter; the second is the method being executed, and the third is the parameter required to execute the method. @Override public object Invoke (object O, Method method, object[] args) throws Throwable {//The actions we want to append to the agent by proxy are written in the Invoke method inside if ("GetName". Equals (Method.getname ())) {System.out.println ("++++++before" + Method.getna  
            Me () + "++++++");  
            Object result = Method.invoke (target, args);  
            System.out.println ("++++++after" + method.getname () + "++++++");  
        return result; }else{Object result = Method.invoke (target, args);  
        return result;  
 }  
  
    }  
}

Package com.meituan.hyt.test3.jdk;

Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Proxy;

Import Com.meituan.hyt.test3.service.UserService;
Import Com.meituan.hyt.test3.service.impl.UserServiceImpl;

public class Main1 {public
	 static void Main (string[] args) {  
		 
        UserService userservice = new Userserviceimpl (); 
  
   //creates a invocationhandler that describes what actions we want the agent to perform
        invocationhandler Invocationhandler = new Myinvocationhandler ( UserService); 
        Create a real Agent with the invocationhandler you just created. The first parameter is the ClassLoader, and the second parameter is which interface the broker implements (the same interface as the agent implements)
        UserService userserviceproxy = (userservice) Proxy.newproxyinstance (Userservice.getclass (). getClassLoader (),  
                Userservice.getclass (). GetInterfaces (), Invocationhandler);  
        System.out.println (Userserviceproxy.getname (1));  
        System.out.println (Userserviceproxy.getage (1));  
    }  


  


Run results

++++++before getname++++++
------getName------
++++++after getname++++++
Tom
------getage------
3, Cglib dynamic Proxy implementation

The

Cglib is an excellent dynamic proxy framework that uses ASM to dynamically generate subclasses of the proxy class in memory, using Cglib to implement dynamic proxy functionality even if the proxy class does not implement any interfaces. Cglib is simple to use and runs much faster than the proxy dynamic proxy for JDK:

Cglib Core classes:
    net.sf.cglib.proxy.enhancer– The main enhancement class,
    net.sf.cglib.proxy.methodinterceptor–, is the primary method of intercepting classes, which are sub-interfaces of callback interfaces, requiring user implementation
  The proxy class of the Java.lang.reflect.Method class of    NET.SF.CGLIB.PROXY.METHODPROXY–JDK can facilitate the invocation of the source object method, such as using:
     object o = Methodproxy.invokesuper (proxy, args);//Although the first argument is a proxy object, there is no question of a dead loop. The

Net.sf.cglib.proxy.MethodInterceptor interface is the most common type of callback (callback) that is often used by agent-based AOP to implement a call to a blocking (intercept) method. This interface defines only one method
public Object Intercept (object object, Java.lang.reflect.Method method,
object[] args, methodproxy Proxy) throws Throwable; The first parameter of

is the proxy pair, and the second and third parameters are the parameters of the method and method that are blocked. The original method may be invoked by using a generic reflection of the Java.lang.reflect.Method object, or by using a Net.sf.cglib.proxy.MethodProxy object. Net.sf.cglib.proxy.MethodProxy is usually preferred to use because it is faster.

[java]  View Plain  copy package com.meituan.hyt.test3.cglib;          import net.sf.cglib.proxy.methodinterceptor;  

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.