Dynamic Agent Java implementation

Source: Internet
Author: User

Think: Add a method to Ibuywatermelon Selectwatermelon ()

The static proxy needs to implement this method in Realsubject, and the proxy also implements the implementation of the method call Realsubject, and if this is done by adding 10 more methods, it will result in a lot of code duplication.

Now, the dynamic proxy (as the name implies, is a proxy object formed at run time, unlike a static proxy that loads proxy objects at compile time).

There are many ways to generate dynamic proxies: The dynamic agent java.lang.reflect.* in the JDK, cglib, etc.

The following example is a self-contained dynamic proxy in the JDK java.lang.reflect.*

Ibuywatermelon (): interface

 Package Com.maggie.dynamicproxy;  Public Interface Ibuywatermelon {    // Agent Event public    abstract  String Buywatermelon ();          Public Abstract void Selectwatermelon ();}

Buywatermelonimpl: Implementation Class

 PackageCom.maggie.dynamicproxy;//can be understood as an agent Public classBuywatermelonimplImplementsIbuywatermelon {Privatesupermarket supermaket;  PublicBuywatermelonimpl (supermarket supermaket) {Super();  This. Supermaket =Supermaket; } @Override PublicString Buywatermelon () {System.out.println ("In" +supermaket.getname () + "Buy watermelon"); return"Watermelon"; } @Override Public voidSelectwatermelon () {System.out.println ("Choose seedless Watermelon"); }}

Proxyfactory: Proxy object Class (core code)

 PackageCom.maggie.dynamicproxy;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy; Public classProxyfactory {//maintain a target object    PrivateObject Target;  Publicproxyfactory (Object target) { This. target=Target; }   //to generate a proxy object for a target object     PublicObject getproxyinstance () {//the core of the dynamic agent involves reflection        returnproxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterf Aces (),NewInvocationhandler () {@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//execute target object methodObject returnvalue =Method.invoke (target, args); returnreturnvalue;    }                }        ); }}

Client Calls

 PackageCom.maggie.dynamicproxy; Public classMain { Public Static voidMain (string[] args) {supermarket Zhaoliu=NewSupermarket (); Zhaoliu.setname ("Zhao Liu Supermarket"); Ibuywatermelon Target=NewBuywatermelonimpl (Zhaoliu);//the object being proxied//Create a proxy objectIbuywatermelon Hourskeeper = (Ibuywatermelon)Newproxyfactory (target). Getproxyinstance ();        Hourskeeper.buywatermelon ();            Hourskeeper.selectwatermelon (); }}

Output

Buy watermelon in Zhao Liu Supermarket and choose seedless watermelon

Now even if the Ibuywatermelon method is added, it is only required to implement in the Buywatermelonimpl, it can be called on the client, there will not be a lot of duplicate code.

From static agents to dynamic agents are around the sale of melon events, in order to facilitate comparison before and after, but the dynamic agent is not finished, the source code mechanism is the core key

public static Object newproxyinstance (ClassLoader loader,class<?>[] Interfaces,invocationhandler h) This method is the key to the entire dynamic agent implementation

Dynamic Agent Java implementation

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.