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