Use of dynamic proxy and its implementation mechanism

Source: Internet
Author: User

I. Use of dynamic proxy

Dynamic proxy(Hereinafter referred toProxyIs a class that implements the list of interfaces specified during the creation of a class. This class has the following actions.

  Proxy InterfaceIs an interface implemented by the proxy class.

Proxy instanceIs an instance of the proxy class.

Each proxy instance has an associatedCall the HandlerObject, which can implement interfacesInvocationHandler. The method call on the proxy instance of one of the proxy interfaces will be assigned to the call handler of the InstanceInvokeMethod, and pass the proxy instance, identify the call Methodjava.lang.reflect.MethodObject andObjectType array. The call handler processes the encoded method call in an appropriate way and returns the result as the result of the method call on the proxy instance.

  

. Its implementation mainly uses the java. lang. reflect. Proxy class and java. lang. reflect. InvocationHandler interface.

< p>

< p>

          }

2. Proxy object: Laptop. java

Laptop System. out. println ("the computer is running ......"}

3. Call processing class: TimeHander. java

        TimeHander                    .object =                             start =         System.out.println("start:"+          Thread.sleep(()(Math.random()*2000          end =         System.out.println("end:"+         System.out.println("total:"+(end-             }

4. Test procedure:

                       Laptop laptop =          TimeHander hander =          IComputer computer =    }


Program running result:

Start: 1369118281186
The computer is running ......
Last: 1369118282849
Total: 1663

 

 

Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)Method returns an instance of the proxy object class. As in the above example, IComputer computer = (IComputer) Proxy. newProxyInstance (laptop. getClass (). getClassLoader (), laptop. getClass (). getInterfaces (), hander); when this statement is executed, a proxy class is dynamically generated through the reflection mechanism, which implements the IComputer interface, in addition, the methods in the interface are overwritten (that is, the proxy class has the same interface as the proxy class). In this proxy class, there is a member variable of the InvocationHandler type, that is, calling the handler, call the handler to enhance the proxy class. After creating the proxy class, call the class loader to load the class to the class storage, and then create an instance object for the proxy class through reflection.

< p>

< p>

          }

2. Proxy object: Tank. java

       Tank                 System.out.println("Tank moving..."                      Thread.sleep( Random().nextInt(10000         }      }

3. Write a Proxy class to generate a Proxy class object for the Proxy object to increase the record running time.

                     Object newProxyInstance(Class interfaces,InvocationHandler h)         StringBuffer methodStr =          String tr = "\r\n"         Method[] methods =                                "    public "+ method.getReturnType()+ " " +method.getName()+"() {" + tr +             "        try {" + tr +             "            java.lang.reflect.Method md = " + interfaces.getName() + "." + "class.getMethod(\""  + method.getName() + "\");" + tr +             "            h.invoke(this,md);" + tr +             "        }catch(Exception e) {e.printStackTrace();}" + tr +             "    }" +                             String src = "package com.test;" + tr +         "import com.test.Moveable;" + tr +         "public class TimeProxy implements " + interfaces.getName() + " {" + tr +         "    private com.test.InvocationHandler h;" + tr +         "    public TimeProxy(com.test.InvocationHandler h) {" + tr +         "        this.h = h;" + tr +         "    }" + tr +         methodStr.toString() + tr +         "}"                  String fileName = System.getProperty("user.dir") + "/src/com/test/TimeProxy.java"         File file =          FileWriter writer =                      JavaCompiler compiler =         StandardJavaFileManager fileMgr = compiler.getStandardFileManager(, ,          Iterable units =         CompilationTask ct = compiler.getTask(, fileMgr, , ,                     Class c = ClassLoader.getSystemClassLoader().loadClass("com.test.TimeProxy"         Constructor constructor = c.getConstructor(InvocationHandler.);          Object m = constructor.newInstance(h);                     }

4. TankProxy. java

             <T> T getBean( Object tank)           (T)Proxy.newProxyInstance(tank.getClass().getInterfaces()[0],                                 start =                 System.out.println("start:"+                                      method.invoke(tank,                  }                     end =                 System.out.println("end:"+                 System.out.println("time:"+(end-                 }    

5. Test procedure:

                   main(String[] args)          Tank tank =          Moveable m =             }

The result of executing this program is:
Start: 1369121253400
Tank moving...
Last: 1369121260078
Time: 6678

The dynamically generated proxy class is as follows:

     TimeProxy                    .h =                             java.lang.reflect.Method md = com.test.Moveable..getMethod("move"             h.invoke(         }   }

  

After reading this example, I should have some knowledge about the implementation mechanism of dynamic proxy!

Summary:

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.