Java Dynamic proxy and cglib dynamic proxy

Source: Internet
Author: User

Dynamic proxy is widely used. Spring, struts, and other frameworks are implemented through dynamic proxy or further encapsulation.

Common dynamic proxy modes include dynamic proxies provided by Java APIs and third-party open-source class libraries cglib dynamic proxies.

The dynamic proxy provided by Java API is implemented based on class reflection, and the classes used include:

Java. Lang. Reflect. invocationhandler;

Java. Lang. Reflect. method;

Java. Lang. Reflect. proxy;

The proxy object is generated through the newproxyinstance () method of the proxy class. The custom dynamic proxy class must implement the invocationhandler interface, which has only one invoke () method.

Cglib dynamically generates proxy objects by generating Java bytecode. Therefore, it depends on the ASM class library for bytecode parsing and processing. The dynamically generated proxy objects actually inherit the real topic classes. This implementation method needs to import the cglib and ASM class libraries. The example used below is cglib-2.2.2.jar, asm-3.3.1.jar. Cglib uses methodinterceptor, and the method is intercept (). This is the interception concept and it is easy to think of the struts2 interceptor.

In comparison, the dynamic proxy provided by Java APIs must be interface-oriented to generate proxy objects. Therefore, the real theme implementation class must implement interfaces.Cglib does not need to be interface-oriented, and can act as a proxy for simple classes.But because the dynamic proxy object inherits the real theme implementation class, the real theme implementation class must not be final.

The following is an example of implementation.

First, to see that the dynamic proxy can dynamically produce different proxy effects based on different classes, we create two interfaces and their implementation classes.

package leon.aj.dynproxy.target;public interface Hello {public String sayHello(String name);}

Implementation class:

package leon.aj.dynproxy.target;public class HelloImpl implements Hello {@Overridepublic String sayHello(String name) {String s = "Hello, "+name;System.out.println(this.getClass().getName()+"->"+s);return s;}}

Another interface and implementation class:

package leon.aj.dynproxy.target;public interface UserDao {public boolean login(String username,String password);}

package leon.aj.dynproxy.target;public class UserDaoImpl implements UserDao {@Overridepublic boolean login(String username, String password) {String user = "("+username+","+password+")";System.out.println(this.getClass().getName()+"-> processing login:"+user);return true;}}

Dynamic proxy classes implemented using Java APIs:

package leon.aj.dynproxy.java;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class JavaDynProxy implements InvocationHandler{private Object target;public Object getProxyInstance(Object target){this.target = target;return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {Object result = null;System.out.println("before target method...");result = method.invoke(target, args);System.out.println("after target method...");return result;}}

Test:

package leon.aj.dynproxy.java;import leon.aj.dynproxy.target.Hello;import leon.aj.dynproxy.target.HelloImpl;import leon.aj.dynproxy.target.UserDao;import leon.aj.dynproxy.target.UserDaoImpl;public class TestJavaProxy {public static void main(String[] args) {JavaDynProxy proxy = new JavaDynProxy();Hello hello = (Hello)proxy.getProxyInstance(new HelloImpl());String s = hello.sayHello("Leon");System.out.println(s);UserDao userDao = (UserDao) proxy.getProxyInstance(new UserDaoImpl());userDao.login("Leon", "1234");System.out.println(userDao.getClass().getName());}}

The following example uses cglib:

package leon.aj.dynproxy.cglib;import java.lang.reflect.Method;import net.sf.cglib.proxy.Enhancer;import net.sf.cglib.proxy.MethodInterceptor;import net.sf.cglib.proxy.MethodProxy;public class CglibProxy implements MethodInterceptor {private Object target;      public Object getProxyInstance(Object target) {      this.target = target;        Enhancer enhancer = new Enhancer();          enhancer.setSuperclass(this.target.getClass());          enhancer.setCallback(this);  // call back method        return enhancer.create();  // create proxy instance    }  @Overridepublic Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable {System.out.println("before target method...");Object result = proxy.invokeSuper(target, args);System.out.println("after target method...");return result;}}

Test class:

Package Leon. AJ. dynproxy. cglib; import leon.aj.dynproxy.tar get. hello; import leon.aj.dynproxy.tar get. helloimpl; import leon.aj.dynproxy.tar get. userdaoimpl; public class testciglib {public static void main (string [] ARGs) {cglibproxy proxy = new cglibproxy (); Hello = (Hello) proxy. getproxyinstance (New helloimpl (); system. out. println (hello. sayhello ("Leon"); userdaoimpl userdao = (userdaoimpl) proxy. getproxyinstance (New userdaoimpl (); userdao. login ("Leon", "1234"); system. out. println (userdao. getclass (). getsuperclass (); // view the parent class of the dynamic proxy instance }}

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.