Java Dynamic proxy implementations (JDK default and Cglib) __JDK

Source: Internet
Author: User
Tags aop reflection throwable

One, JDK Dynamic proxy class   Java code public interface IService {Boolean getservice (String data); }

Java code public class Serviceimpl implements IService {public boolean getservice (String data) {if ("A")           . Equals (data)) {return true;           else {return false; }       }      }

  Java code   import java.lang.reflect.invocationhandler;   import  java.lang.reflect.method;      public class servicehandler implements  invocationhandler {       private Object delegateObj;          public servicehandler (object delegateobj)  {           this.delegateObj = delegateObj;        }          public object invoke (object  Proxy, method method, object[] args)                 throws Throwable {            system.out.println ("Begin transaction ...");            boolean rtn =  (Boolean)  method.invoke (Delegateobj, args);            system.out.println ("End transaction ...");            return rtn;       }     }  

  Java code   import java.lang.reflect.proxy;      public class test  {       public static void main (string args[])  {            ServiceImpl si = new  Serviceimpl ();              servicehandler sh  = new servicehandler (SI);               IService is =  (IService)  proxy.newproxyinstance (Si.getclass ()                     .getclassloader (),  si.getclass (). Getinterfaces (),  sh);               is.getservice ("A");       }  }  

Second, the cglib dynamic proxy class


The Figure 1:cglib Library and ASM bytecode framework diagram shows a diagram of the and cglib packages and some frameworks and languages. Note that some frameworks, such as spring AOP and hibernate, are needed to meet dynamic proxies and cglib packages that often use JDK simultaneously. Hiberater uses the JDK dynamic proxy to implement a transaction management adapter specifically for the Webshere application server; Spring AOP, if the Cglib package is not enforced, the default is to use the dynamic proxy of JDK to proxy the interface.

Java code public class Target {public string Execute () {string message = "----------Test ()----------";           SYSTEM.OUT.PRINTLN (message);       return message; }   }

  Java code   import net.sf.cglib.proxy.methodinterceptor;   import  net.sf.cglib.proxy.methodproxy;   import java.lang.reflect.method;      Public  class MyMethodInterceptor implements MethodInterceptor {          public object intercept (object object, method method,  object[] args,                Methodproxy methodproxy)  throws Throwable {            system.out.println (">>>methodinterceptor start ...");            object result = methodproxy.invokesuper (Object, args);            system.out.println (">>>methodinterceptor  ending ... ");           return  "Hahahh";       }   }  

  Java code   import net.sf.cglib.proxy.enhancer;      public class  testcglibproxy {       public static void main (String  Rags[])  {           target target = new  target ();           testcglibproxy test =  new testcglibproxy ();           Target  proxytarget =  (Target)  test.createproxy (target.class);            string res = proxytarget.execute ();            system.out.println (res);       }          public object createproxy (class targetclass)  {             enhancer enhancer = new enhancer ();            enhancer.setsuperclass (targetclass);            enhancer.setcallback (New mymethodinterceptor ());            return enhancer.create ();       }  }  

Cglib package of basic code is very small, when learning to have a certain difficulty, mainly is the lack of documentation, which is an open source software deficiencies. The current version of Cglib is (2.1.2), mainly composed of parts: Net.sf.cglib.core
Low-level bytecode manipulation classes; Most of them are related to ASM. Net.sf.cglib.transform
Classes for class file transformations in runtime or build time Net.sf.cglib.proxy
Classes for proxy creation and method interceptions Net.sf.cglib.reflect
Classes for a faster reflection and C#-style delegates Net.sf.cglib.util
Collection Sorting Utilities Net.sf.cglib.beans
JavaBean Related Utilities

Most of the time, just to create a proxy dynamically, you only need to use a few APIs in the agent package.

As we discussed earlier, the Cglib package is a high-level level above the ASM. is useful for proxies that do not implement interfaces. In essence, it is by dynamically generating a subclass to overwrite the desired proxy class is not final method, and set the callback, the original class of each method call will be converted to call the user-defined blocking method (interceptors), which is faster than the JDK dynamic proxy method.

Net.sf.cglib.proxy.MethodInterceptor can meet any interception (interception) needs when it may be excessive in some cases. To simplify and improve performance, the Cglib package provides a number of specialized callback (callback) types. For example: Net.sf.cglib.proxy.FixedValue
To improve performance, the Fixedvalue callback is useful for forcing a particular method to return a fixed value. Net.sf.cglib.proxy.NoOp
The NoOp callback assigns the method call directly to the implementation of the method in the parent class. Net.sf.cglib.proxy.LazyLoader
You can use the Lazyloader callback when the actual object requires deferred loading. Once the actual object is loaded, it is used by each method that invokes the proxy object. Net.sf.cglib.proxy.Dispatcher
The Dispathcer callback and the Lazyloader callback have the same characteristics, but the method of loading the object is always called when the proxy method is invoked. Net.sf.cglib.proxy.ProxyRefDispatcher
The Proxyrefdispatcher callback is the same as the dispatcher, and it can pass the proxy object as a parameter to the Load object method.

The method of proxy class is often used with callbacks (callback), and when it is you can also use Net.sf.cglib.proxy.CallbackFilter selective callback (callback) for some methods, This thoughtful control feature is not in the JDK's dynamic proxies. In the JDK proxy, calls to the Java.lang.reflect.InvocationHandler method are valid for the proxy class's methods.

Use a methodinterceptor in order to better use the proxy, we can replace the net.sf.cglib.proxy.NoOp callback with our own defined Methodinterceptor type callback (callback). When calls to all methods in the agent are invoked, the Methodinterceptor type of blocking (intercept) method is turned on, and the corresponding method of the underlying object is called in the blocking method.

Use a callbackfilter

Summary glib is a powerful, High-performance code generation package. It provides a proxy for classes that do not implement interfaces and provides a good complement to the dynamic proxy for JDK. It uses bytecode to process the framework ASM at the bottom. The principle is to produce a subclass of the proxy class, which overrides all methods that are not final for the class to be represented. It is faster than the JDK dynamic proxy that uses Java reflection. Typically, you can use the JDK's dynamic proxy to create proxies, and Cglib is a good choice when you want to broker classes that do not implement interfaces or for better performance.

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.