AOPThe idea of proxy is Aspect-Oriented. Dynamic proxy technology is added. With AOP proxy, we can add some new businesses without modifying the original business classes. Shows the implementation idea:
The following is a simple example.Code:
1,DogInterface
Public interface dog {public void Info (); Public void run ();}
2,GundogImplementation class
Public class gundog implements dog {@ overridepublic void Info () {system. out. println ("it's a dog") ;}@ overridepublic void run () {system. out. println ("this dog run quickly ");}}
3,DogutilClass, New Processing Method
Public class dogutil {public void Method1 () {system. out. println ("========= this is the first method ===========");} public void method2 () {system. out. println ("========= this is the second method ========= ");}}
4,MyinvocationhandlerClass needs to be implementedInvocationhandlerAbstract Interface
Import Java. lang. reflect. invocationhandler; import Java. lang. reflect. method; public class myinvocationhandler implements invocationhandler {// Private object target to be proxy; Public void settarget (Object target?#this.tar get = target;} // when you execute all the methods of dynamic proxy, will be replaced with the following invoke method @ overridepublic object invoke (Object proxy, method, object [] ARGs) throws throwable {dogutil du = new dogutil (); // execute the Method1 method du. method1 (); // use target as the main call to execute method object result = method. invoke (target, argS); // then execute the method2 method du. method2 (); return result ;}}
5FactoryMyproxyfactoryClass, get dynamic proxy through reflection mechanism
Import Java. lang. reflect. proxy; public class myproxyfactory {// generate dynamic proxy public static object getproxy (object target) throws exception {// create a myinvocationhandler object myinvocationhandler handler = new myinvocationhandler (); // set the target object handler for myinvocationhandler. settarget (target); // create and return a dynamic proxy return proxy. newproxyinstance (target. getclass (). getclassloader (), target. getclass (). getinterfaces (), Handler );}}
6, TestTestaopClass
Public class testaop {/*** @ Param ARGs */public static void main (string [] ARGs) throws exception {// create an original gundog object as targetdog target = new gundog (); // create a dynamic proxy dog = (DOG) myproxyfactory with the specified target. getproxy (target); dog.info (); dog. run ();}}