"reprint" Java Dynamic Agent

Source: Internet
Author: User
Tags object object throwable

Transferred from: http://blog.csdn.net/heyutao007/article/details/49738887

The interception capabilities of AOP are implemented by dynamic proxies in Java. To be blunt, it is to increase the tangent logic on the basis of the target class, to generate an enhanced target class (which is either before the target class function executes, or after the target class function executes, or when the target class function throws an exception). Different cut-in times correspond to different types of interceptor, such as Beforeadviseinterceptor,afteradviseinterceptor and throwsadviseinterceptor, etc.).


So how does the dynamic agent implement the advise to weave the facet logic into the target class method? Let's go through the details and implement the two dynamic proxies used in Aop.

The source code of AOP uses two kinds of dynamic agents to realize interception and cut-in function: JDK Dynamic agent and Cglib dynamic Agent. Both methods exist at the same time, each has its merits and demerits. the JDK Dynamic Agent is implemented by the reflection mechanism inside java, and the Cglib dynamic agent is implemented by 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 cache the asm-generated classes to solve the asm-generated class-process inefficiencies). It is also important to note that the application premise of the JDK dynamic agent must be the target class based on the unified Interface. The JDK dynamic agent cannot be applied without the above Premise. It can be seen that the JDK dynamic agent has certain limitations, Cglib this Third-party class library implementation of dynamic proxy application more extensive, and more efficient Advantages.

1. Define interfaces and implementations [java]View Plaincopy print?
    1. Package com.meituan.hyt.test3.service;
    2. Public interface UserService {
    3. public String getName (int id);
    4. public Integer getage (int id);
    5. }


[java]View Plaincopy print?
  1. Package com.meituan.hyt.test3.service.impl;
  2. Import com.meituan.hyt.test3.service.UserService;
  3. Public class Userserviceimpl implements UserService {
  4. @Override
  5. public String getName (int Id) {
  6. System.out.println ("------getName------");
  7. return "Tom";
  8. }
  9. @Override
  10. public Integer getage (int Id) {
  11. System.out.println ("------getage------");
  12. return 10;
  13. }
  14. }

2, JDK Dynamic Agent implementation [java]View Plaincopy print?
  1. Package com.meituan.hyt.test3.jdk;
  2. Import java.lang.reflect.InvocationHandler;
  3. Import java.lang.reflect.Method;
  4. Public class Myinvocationhandler implements Invocationhandler {
  5. Private Object target;
  6. Myinvocationhandler () {
  7. Super ();
  8. }
  9. Myinvocationhandler (Object Target) {
  10. Super ();
  11. This.target = target;
  12. }
  13. @Override
  14. public Object Invoke (object o, method method, object[] Args) throws throwable {
  15. if ("getName". equals (method.getname ())) {
  16. System.out.println ("++++++before" + method.getname () + "++++++");
  17. Object result = Method.invoke (target, args);
  18. System.out.println ("++++++after" + method.getname () + "++++++");
  19. return result;
  20. }else{
  21. Object result = Method.invoke (target, args);
  22. return result;
  23. }
  24. }
  25. }

[java]View Plaincopy print?
  1. Package com.meituan.hyt.test3.jdk;
  2. Import com.meituan.hyt.test3.service.UserService;
  3. Import com.meituan.hyt.test3.service.impl.UserServiceImpl;
  4. Import java.lang.reflect.InvocationHandler;
  5. Import java.lang.reflect.Proxy;
  6. Public class Main1 {
  7. public static void main (string[] Args) {
  8. UserService userservice = new Userserviceimpl ();
  9. Invocationhandler Invocationhandler = new Myinvocationhandler (userservice);
  10. UserService userserviceproxy = (userservice) proxy.newproxyinstance (userservice.getclass (). getClassLoader (),
  11. Userservice.getclass (). getinterfaces (), invocationhandler);
  12. System.out.println (userserviceproxy.getname (1));
  13. System.out.println (userserviceproxy.getage (1));
  14. }
  15. }


Run results

++++++before getname++++++
------getName------
++++++after getname++++++
Tom
------getage------
10

3, cglib Dynamic Agent implementation

Cglib is an excellent dynamic proxy framework, which uses ASM to dynamically generate the subclass 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 easy to use, and it runs much faster than the JDK proxy dynamic agent:

Core classes of Cglib:
net.sf.cglib.proxy.enhancer– Major Enhancement classes
net.sf.cglib.proxy.methodinterceptor– The Main method interception class, which is a sub-interface of the callback interface, requires the user to implement
The proxy class of the Java.lang.reflect.Method class of NET.SF.CGLIB.PROXY.METHODPROXY–JDK can easily implement the invocation of the source object method, such as Using:
Object o = Methodproxy.invokesuper (proxy, args);//although The first parameter is a proxy object, there is no problem with the dead loop.

The Net.sf.cglib.proxy.MethodInterceptor interface is the most common type of callback (callback), and it is often used by proxy-based AOP to implement a call to intercept (intercept) METHODS. This interface only defines a method
public object intercept (object object, java.lang.reflect.Method Method,
object[] args, methodproxy Proxy) throws throwable;

The first parameter is the proxy pair image, the second and third parameters are the parameters of the intercepted method and method, Respectively. The original method may be called by using the general reflection of the Java.lang.reflect.Method object, or by using the Net.sf.cglib.proxy.MethodProxy Object. Net.sf.cglib.proxy.MethodProxy is usually preferred because it is faster.

[java]View Plaincopy print?
  1. Package com.meituan.hyt.test3.cglib;
  2. Import net.sf.cglib.proxy.MethodInterceptor;
  3. Import net.sf.cglib.proxy.MethodProxy;
  4. Import java.lang.reflect.Method;
  5. Public class Cglibproxy implements Methodinterceptor {
  6. @Override
  7. public Object Intercept (object o, method method, object[] args, methodproxy methodproxy) throws Throwable {
  8. System.out.println ("++++++before" + methodproxy.getsupername () + "++++++");
  9. System.out.println (method.getname ());
  10. Object O1 = Methodproxy.invokesuper (o, args);
  11. System.out.println ("++++++before" + methodproxy.getsupername () + "++++++");
  12. return o1;
  13. }
  14. }


[java]View Plaincopy print?
  1. Package com.meituan.hyt.test3.cglib;
  2. Import com.meituan.hyt.test3.service.UserService;
  3. Import com.meituan.hyt.test3.service.impl.UserServiceImpl;
  4. Import net.sf.cglib.proxy.Enhancer;
  5. Public class Main2 {
  6. public static void main (string[] Args) {
  7. Cglibproxy cglibproxy = new Cglibproxy ();
  8. Enhancer enhancer = New Enhancer ();
  9. Enhancer.setsuperclass (userserviceimpl.   class);
  10. Enhancer.setcallback (cglibproxy);
  11. UserService o = (userservice) enhancer.create ();
  12. O.getname (1);
  13. O.getage (1);
  14. }
  15. }


Running Result: ++++++before cglib$getname$0++++++
GetName
------getName------
++++++before cglib$getname$0++++++
++++++before cglib$getage$1++++++
Getage
------getage------
++++++before cglib$getage$1++++++

"reprint" Java Dynamic Agent

Related Article

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.