Java Dynamic Agent

Source: Internet
Author: User

First define an interface

 Public Interface Subject {    void  printf ();}

interface implemented by proxy class

 Public class Implements Subject {    @Override    publicvoid  printf () {        System.out.println ( "This is a realsubject ' s printf ()");    }    }

Define Subjectinvocationhandler Implement Invocationhandler interface

 Public classSubjectinvocationhandlerImplementsinvocationhandler{//the object being proxied    PrivateObject Proxy;  PublicSubjectinvocationhandler (Object proxy) { This. Proxy =proxy; }        /*** Proxy Object Calling method * method called methods * Args Call method's parameters * Return call method returned value*/@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Subjectinvocationhandler Invoke Prepare"); Object result= Method.invoke ( This. Proxy, args); System.out.println ("Subjectinvocationhandler invoke Post"); returnresult; }}

Final Test

 Public classProxytest { Public Static voidMain (string[] args) {realsubject realsubject=NewRealsubject (); Class<?> CLZ =Realsubject.getclass (); //get class for proxy classesClass<?> PROXYCLZ =Proxy.getproxyclass (Clz.getclassloader (), clz.getinterfaces ()); Try {            //get the constructor with the Invocationhandler parameterconstructor<?> Constructor = Proxyclz.getconstructor (Invocationhandler.class); //instantiating a proxy object with a constructorSubject Proxysubject = (Subject) constructor.newinstance (NewSubjectinvocationhandler (realsubject));        Proxysubject.printf (); } Catch(Exception e) {e.printstacktrace (); }                //using the method in proxy one stepSubject Proxysubject = (Subject) proxy.newproxyinstance (Clz.getclassloader (), clz.getinterfaces (),NewSubjectinvocationhandler (realsubject));            Proxysubject.printf (); }}

Java Dynamic Agent

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.