Dynamic proxy in design mode and design mode proxy

Source: Internet
Author: User

Dynamic proxy in design mode and design mode proxy
I. Dynamic proxy Concept

Dynamic proxy can be divided into JDK dynamic proxy and cglib dynamic proxy.

Jdk dynamic proxy is implemented by the Java internal reflection mechanism, while cglib dynamic proxy is implemented by asm at the underlying layer.

In general, the reflection mechanism is more efficient in the process of generating classes, while asm is more efficient in the execution process after the classes are generated (you can cache the classes generated by asm, this solves the problem of inefficiency in the Process of asm generation class ).

Note: The premise of jdk dynamic proxy must be that the target class is based on a unified interface. Without the preceding prerequisites, jdk dynamic proxy cannot be applied.

It can be seen that jdk dynamic proxy has some limitations. cglib, a third-party class library, implements a wider range of dynamic proxy applications and has more efficiency advantages.

Ii. JDK dynamic proxy

The following code uses the proxy mode to convert uppercase and lowercase characters.

Define interfaces and implementation classes:

ISomeService interface:

Package com. ietree. basicskill. designpattern. dynamicproxy. jdk;/*** interface Class ** @ author Root */public interface ISomeService {String doFirst (); void doSecond ();}

SomeServiceImpl implementation class:

Package com. ietree. basicskill. designpattern. dynamicproxy. jdk;/*** implementation class ** @ author Root */public class SomeServiceImpl implements ISomeService {@ Override public String doFirst () {System. out. println ("execute doFirst ()... "); String result =" abcde "; return result ;}@ Override public void doSecond () {System. out. println ("execute doSecond ()... ");}}

JDK dynamic Proxy:

Package com. ietree. basicskill. designpattern. dynamicproxy. jdk; import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy; public class Main {public static void main (String [] args) {final ISomeService target = new SomeServiceImpl (); // use the JDK Proxy dynamic Proxy, it is required that the target class and Proxy class must implement the same interface, because its underlying execution principle is the same as that of the static Proxy ISomeService service = (ISomeService) Proxy. newProxyInstance (// Target. getClass (). getClassLoader (), // All interfaces implemented by the target class target. getClass (). getInterfaces (), new InvocationHandler () {// proxy: proxy Object // method: Target method // args: parameter list of the target method @ Override public Object invoke (Object proxy, method method, Object [] args) throws Throwable {// call the target method Object result = Method. invoke (target, args); if (result! = Null) {result = (String) result ). toUpperCase () ;}return result ;}}); String result = service. doFirst (); System. out. println (result); service. doSecond ();}}
Iii. cglib dynamic proxy

Cglib is an excellent dynamic proxy framework. At the underlying layer, it uses ASM to dynamically generate a subclass of the proxy class in the memory. Using CGLIB can implement the dynamic proxy function even if the proxy class does not implement any interfaces. CGLIB is easy to use and runs much faster than JDK's Proxy dynamic Proxy:

CGLIB core class:
Net. sf. cglib. proxy. Enhancer-Main enhancement class
Net. sf. cglib. proxy. MethodInterceptor-main method interception class, which is a subinterface of the Callback interface and needs to be implemented by the user
Net. sf. cglib. proxy. MethodProxy-JDK's java. lang. reflect. Method class proxy class, you can conveniently call the source object Method, such as using:
Object o = methodProxy. invokeSuper (proxy, args); // although the first parameter is a proxy Object, there will be no endless loops.

The net. sf. cglib. proxy. MethodInterceptor interface is the most common callback type. It is often used by proxy-based AOP to call intercept methods. This interface only defines one method.
Public Object intercept (Object object, java. lang. reflect. Method method, Object [] args, MethodProxy proxy) throws Throwable;

The first parameter is the proxy object, and 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.

The following procedures enable case-insensitive conversion:

Implementation class SomeService:

Package com. ietree. basicskill. designpattern. dynamicproxy. cglib;/*** implementation class ** @ author Root */public class SomeService {public String doFirst () {System. out. println ("execute doFirst ()... "); String result =" abcde "; return result;} public void doSecond () {System. out. println ("execute doSecond ()... ");}}

Proxy class MyCglibFactory:

Package com. ietree. basicskill. designpattern. dynamicproxy. 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 MyCglibFactory implements MethodInterceptor {private SomeService target; public MyCglibFactory () {super (); target = new SomeService ();} public SomeService myCglibCreator (){ // Create the enhancement object Enhancer enhancer = new Enhancer (); // specify the target class, that is, the parent class enhancer. setSuperclass (SomeService. class); // set the callback interface object enhancer. setCallback (this); return (SomeService) enhancer. create () ;}@ Override public Object intercept (Object obj, Method method, Object [] args, MethodProxy proxy) throws Throwable {// call the target method Object result = Method. invoke (target, args); if (result! = Null) {result = (String) result). toUpperCase () ;}return result ;}}

Test:

package com.ietree.basicskill.designpattern.dynamicproxy.cglib;public class Main {    public static void main(String[] args) {        SomeService service = new MyCglibFactory().myCglibCreator();                String result = service.doFirst();        System.out.println("result = " + result);        service.doSecond();    }}

Running result:

Execute doFirst ()... result = ABCDE execute doSecond ()...

 

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.