Dynamic proxy mode in Java:

Source: Internet
Author: User

API for generating proxy objects in JDK

Agent Class Package: Java.lang.reflect.Proxy
The JDK implementation agent only needs to use the Newproxyinstance method, but the method needs to receive three parameters, the complete wording is:

Static Object newproxyinstance (ClassLoader loader, class<?>[] Interfaces,invocationhandler h)

Note that this method is a static method in the proxy class, and the three parameters received are:

    • ClassLoader loader,: Specifies that the current target object uses the class loader, and that the method to get the loader is fixed
    • Class<?>[] interfaces,: Type of interface implemented by the target object, using generic mode acknowledgment type
    • InvocationHandler h: Event handling, the method that triggers the event handler when the method of the target object is executed, passing the method of the current execution target object as a parameter

Member.java Entity classes:

 PackageCom.dx.dynamicproxy; Public classMember {Private intID; PrivateString name;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicMember (intID, String name) {        Super();  This. ID =ID;  This. Name =name; } @Override PublicString toString () {return"Member [id=" + ID + ", name=" + name + "]"; }}
View Code

Imemberservice.java

 Package Com.dx.dynamicproxy;  Public Interface Imemberservice {    public  String Create (Member Member);}

Memberserivceimpl.java

 Package Com.dx.dynamicproxy;  Public class Implements Imemberservice {    public  String Create (Member Member) {        System.out.println (" Create member: "+ member);         return "SUCCESS";    }}

Memberserviceimplproxy.java Dynamic proxy class

 PackageCom.dx.dynamicproxy;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method; Public classMemberserviceimplproxyImplementsInvocationhandler {PrivateObject obj;  Publicmemberserviceimplproxy (Object obj) { This. obj =obj; }     PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {before (method); Object Resultvalue= Method.invoke (obj, args);//Real Call method operationAfter (method); returnResultvalue; }    Private voidbefore (method) {System.out.println ("Before" +method); }    Private voidAfter (method) {System.out.println ("After" +method); }}

Proxyfactory.java Dynamic Agent Factory (more general)

 PackageCom.dx.dynamicproxy;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;/*** Creating dynamic Proxy objects Dynamic proxies do not need to implement interfaces, but need to specify interface types*/ Public classProxyfactory {//maintain a target object    PrivateObject Target;  Publicproxyfactory (Object target) { This. target =Target; }    /*** Generate proxy object for target object*/     PublicObject getproxyinstance () {ClassLoader ClassLoader=Target.getclass (). getClassLoader (); Class<?>[] Interfaces =Target.getclass (). Getinterfaces (); Invocationhandler Invocationhandler=NewInvocationhandler () { PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {before (method); //execute target object methodObject returnvalue =Method.invoke (target, args);                After (method); returnreturnvalue;        }        }; returnproxy.newproxyinstance (ClassLoader, interfaces, Invocationhandler); }    Private voidbefore (method) {System.out.println ("Before" +method); }    Private voidAfter (method) {System.out.println ("After" +method); }}
Client.java Invocation Example:
 PackageCom.dx.dynamicproxy; Public classClient { Public Static voidMain (string[] args) {Imemberservice Basememberservice=NewMemberserivceimpl (); //Invocationhandler handler = new Memberserviceimplproxy (basememberservice);//class<?> ClassType = Handler.getclass ();//Imemberservice Memberservice = (imemberservice) proxy.newproxyinstance (Classtype.getclassloader (),//Basememberservice.getclass (). Getinterfaces (), handler); //orImemberservice Memberservice = (imemberservice)Newproxyfactory (Basememberservice). Getproxyinstance (); Member Member=NewMember (1, "Test"); //execute the Invoke methodString result =Memberservice.create (member);    SYSTEM.OUT.PRINTLN (result); }}

Dynamic proxy mode in Java:

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.