The memory is inferior to the bad writer 46-java Interceptor-thoroughly understand the concept of dynamic agent (1)

Source: Internet
Author: User

Dynamic Agent technology is a very important part of the entire Java technology system, which is the basis for us to learn more about the Java framework, and is one of the basic knowledge to understand the framework of spring in depth.

1, the concept of the agent in Java

Dynamic Agent technology is the proxy object used to produce an object. It seems that you are confused, as if you can't use it.
(The following example is partly from the Internet)
Take a real-life example: singers or stars have their own brokers, the broker is their agent, when we need to find a star performance, we can not directly find the star, can only be a star agent. For example Wangbaoqiang in real life is very famous, can sing, can Dance, will be filming. Wangbaoqiang before the famous, in their village farming, we can directly find him singing, dancing, filming, Wangbaoqiang famous, he found a broker, this broker is Wangbaoqiang agent (agent), when we need to find Wangbaoqiang performance, can not directly find Bao Qiang (Wangbaoqiang said, You find my agent!), so the value of Wangbaoqiang this agent exists is to intercept our direct access to Wangbaoqiang!
This example is the same as we do in the development, we are in the development of the reason to produce an object proxy object, mainly used to intercept the real business object access.
So what should be the method of the proxy object? The proxy object should have the same method as the target object.
1. The value of proxy object is mainly used to intercept access to real business objects.
2. The proxy object should have the same method as the target object (the real business object).
Wangbaoqiang (Real business object) will sing, Can Dance, will be filming, we can not directly find him singing, dancing, filming, can only find his agent (Agent object) singing, dancing, filming, a person to want to become Andy Lau's Wangbaoqiang, then he must appear to have and wangbaoqiang the same behavior (can sing, will dance, will be filming), Wangbaoqiang have what method, he (agent) will have what method, we find Wangbaoqiang agent singing, dancing, filming, but agents do not really know how to sing, dance, filming, really know how to sing, dance, filming is Wangbaoqiang, in the real example is we want to find Wangbaoqiang singing, dancing, filming , then you can only find his agent, pay his agent, then the agent let Wangbaoqiang to sing, dance, filming.

2. Classes and methods for implementing dynamic proxies in Java

Java provides a "Java.lang.reflect.Proxy" class after JDK1.5, using a newproxyinstance method provided by the "Proxy" class to create a proxy object for an object:
Static Object newproxyinstance (ClassLoader loader, Class

3. Define the object's behavior interface

In Java, if you want to produce an object's proxy object, then this object must have an interface, so our first step is to design the interface of this object, and define the behavior (method) of the object in the interface.

package com.proxy;/** * 一个演员对象的接口,需要会唱歌和跳舞 * @author 范芳铭 */publicinterface  Actor {     String sing(String name);     String dance(String name);}
4. Define target object class (concrete implementation object)
 PackageCom.proxy;/** * Wangbaoqiang is an actor, he can sing and dance * @author Fan Fangming * * Public  class Wangbaoqiang implements Actor{    PrivateString name; Public Wangbaoqiang(){ This. Name ="Wangbaoqiang"; } PublicStringSing(String name) {System.out.println ( This. GetName () +"Start singing."+name+"Song!! ");return "The singing is over, thank you!" "; } PublicStringDance(String name) {System.out.println ( This. GetName () +"Start jumping"+name+"Dance!! ");return "Dance is done, thank you!" "; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; }}
5. Define proxy classes that generate proxy objects
 PackageCom.proxy;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;/** * Actor's agent, he can't sing and dance, but brokers can find people who can sing and dance * @author Fan Fangming * * Public  class actorjingjiren {    //Design a class variable remember the target object to which the proxy class is to be proxied    PrivateActor actor =NewWangbaoqiang ();//via broker, return the object of Wangbaoqiang     PublicActorGetProxy() {//using proxy.newproxyinstance (ClassLoader loader, class<?>[] interfaces,        ///Invocationhandler h) Returns the proxy object for an object        return(Actor) Proxy.newproxyinstance (Actorjingjiren.class. getClassLoader (), Actor.getclass (). Getinterfaces (),NewInvocationhandler () {/** * Invocationhandler interface only defines an invoke method, so for such an interface, * we do not have to define a class to implement the interface, but directly to the                      Using an anonymous inner class to implement the interface, new * Invocationhandler () {} is an anonymous implementation class for the Invocationhandler interface *                     * In the Invoke method encoding specifies the proxy object returned by the job proxy: Pass the proxy object in itself. * Method: Pass in the proxy object's current invocation. Args: Pass in the method parameters. * So we can use Method.getname () in the Invoke method to know which method of the proxy object is currently being called */                    @Override                     PublicObjectInvoke(Object Proxy, Method method, object[] args)throwsThrowable {if(Method.getname (). Equals ("Sing") {System.out.println ("I am his agent, and have something to look for me first!" ");//proxy object invokes the Sing method of the real target object to process the user request                            returnMethod.invoke (actor, args); }if(Method.getname (). Equals ("Dance")) {//proxy object invokes the dance method of the real target object to process the user requestSystem.out.println ("I am his agent, and have something to look for me first!" ");returnMethod.invoke (actor, args); }return NULL;    }                }); }}
6. Test class to invoke dynamic proxy
 PackageCom.proxy;/** * Test class, find the broker to make a singing and dancing request on the line * * @author Fan Fangming * * Public  class proxytest {     Public Static void Main(string[] args) {//Find brokers FirstActorjingjiren proxy =NewActorjingjiren ();//Get related actors by broker (Agent object)Actor p = proxy.getproxy ();//Let the actors singString RetValue = p.sing ("No Thief in the world."); System.out.println (RetValue);//Let the actors danceString value = P.dance ("Phoenix Legend");    System.out.println (value); }}
7. Operation Result

I'm his agent, I have something to look for first!
Wangbaoqiang began to sing the world No Thief song!!
Singing is over, thank you!
I'm his agent, I have something to look for first!
Wangbaoqiang began to jump the Phoenix legendary dance!!
Dance is done, thank you!

The memory is inferior to the bad writer 46-java Interceptor-thoroughly understand the concept of dynamic agent (1)

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.