Dynamic proxy is the core of AOP. A simple dynamic proxy is to create a proxy object and then enhance the original method. Very abstract. The example is king. JDK provides the Implementation of Dynamic proxy, but it is for the interface. To implement dynamic proxy, you need the interface of the proxy object. This is a drawback. You cannot write an interface to the proxy object to implement dynamic proxy, which is sometimes troublesome in Web development. In this way, you can directly change the bytecode, to rewrite a subclass, You need to enhance the method. However, if the method in this class is defined as final, it cannot be used.
1. interface to be implemented by the delegate class
1 package dynamic proxy; 2 3 Public interface heelo {4 string sayhello (); 5 void saygoodble (); 6 7}
2. Specific implementation of the delegate class
1 package dynamic proxy; 2 3 Public class helloimpl implements heelo {4 5 @ override 6 Public String sayhello () {7 // todo auto-generated method stub 8 return "heelo "; 9 10} 11 12 @ override13 public void saygoodble () {14 // todo auto-generated method stub15 system. out. println ("goodbye"); 16 17} 18 19}
3. Handler (advice)
Package dynamic proxy; import Java. lang. reflect. invocationhandler; import Java. lang. reflect. method; public class hellohander implements invocationhandler {helloimpl hip = NULL; // pass in the proxy object public hellohander (helloimpl hip) {This. hip = hip ;}@ override // public object invoke (Object arg0, method arg1, object [] arg2) throws throwable {// todo auto-generated method stub system. out. println ("before" + arg1.getname ()); Object res = arg1.invoke (HIP, arg2); // The original Logic System of the object to be proxy. out. println ("after" + arg1.getname (); Return res; // pay attention to the execution order. }}
4. Client
Package dynamic proxy; import Java. lang. reflect. proxy; public class test {public static void main (string [] ARGs) {// todo auto-generated method stub helloimpl HL = new helloimpl (); // target, the proxy object hellohander HH = new hellohander (HL); // creates a processor, similar to advice // creates a proxy object, proxy heelo H = (heelo) proxy for all methods of target. newproxyinstance (HL. getclass (). getclassloader (), HL. getclass (). getinterfaces (), HH); // call the sayheelo method system. out. println (H. sayhello (); system. out. println (); // call saybye H. saygoodble ();}}
Dynamic proxy (JDK)