First we define an interface
Public Interface Sayservice { publicvoid Say ();}
View Code
Then implement this interface
Public class Implements Sayservice { @Override publicvoid say () { System.out.println ("I Want to go shoping. " ); }}
View Code
Define a dynamic proxy class, each dynamic proxy class must implement Invocationhandler this interface
ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method; Public classDynamicproxyImplementsInvocationhandler {//the real object we're going to be acting for PrivateObject object; PublicDynamicproxy (Object object) { This. Object =object; } @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Before Go shoping"); //when a contemporary object invokes a method of a real object, it automatically jumps to the Invoke method of the handler object associated with the proxy object .Method.invoke (object, args); System.out.println ("After Go shoping"); return NULL; }}View Code
Defining test methods
Public classTestproxy { Public Static voidMain (string[] args) {//the object to be proxiedSayservice Sayimpl =NewSayimpl (); //to proxy which object, it is necessary to transfer the object in, and finally through its real object to invoke the method'sInvocationhandler handler =NewDynamicproxy (Sayimpl); //proxy.newproxyinstance--Creating a proxy object//Handler.getclass (). getClassLoader ()---Load proxy object//Sayimpl.getclass (). Getinterfaces ()--the interface provided for the proxy object is the interface implemented by the real object, which means that we are going to proxy the real object, so that we can invoke the method in the interface//Invocationhandler This object on the handler-associationSayservice Sayservice =(Sayservice) proxy.newproxyinstance (Handler.getclass (). getClassLoader (), Sayimpl.getclass (). GETINTERFAC ES (), handler); Sayservice.say (); }}View Code
Log for console printing
Before Go shoping
I want to go shoping.
After Go shoping
Java Dynamic Agent