Public Interface MyInterface { void dosomething (); void somethingelse (String param);}
Public class Implements myinterface{ @Override publicvoid dosomething () { // TODO auto-generated Method stub Print ("Start calling DoSomething method"); } @Override publicvoid somethingelse (String param) { // TODO auto-generated Method stub Print ("Start calling somethingelse method; parameters" +param);} }
Public classSimpleproxyImplementsmyinterface{PrivateMyInterface MyInterface; Publicsimpleproxy (MyInterface myinterface) { This. myinterface=MyInterface; } @Override Public voiddosomething () {//TODO auto-generated Method StubPrint ("Business logic dosomething ..."); Myinterface.dosomething (); } @Override Public voidsomethingelse (String param) {//TODO auto-generated Method StubPrint ("Business logic else ..."); Myinterface.somethingelse (param); } Public Static voidconsumer (MyInterface myinterface) {myinterface.dosomething (); Myinterface.somethingelse ("Bubu."); } Public Static voidMain (string[] args) {Consumer (Newrealobject ()); Consumer (NewSimpleproxy (NewRealobject ())); }}
The following is a dynamic proxy
To customize a call processor:
/*** Call Processor <p>* Dynamic Agent can redirect all calls to the calling processor*/ Public classDynamicproxyhandleImplementsinvocationhandler{PrivateObject proxied; PublicDynamicproxyhandle (Object object) { This. proxied=object; } @Override PublicObject Invoke (Object Proxy,method method,object[] args)throwsillegalaccessexception, IllegalArgumentException, invocationtargetexception {print ("proxy class:" +proxy.getclass () + "method:" +method+ "args:" +args); if(Method.getname (). Equals ("DoSomething") {print ("Agent detected that DoSomething was called"); }//if (args!=null) {//For (Object Object:args) {//print ("=====" +object);// }// } returnMethod.invoke (proxied, args); }}
Public classSimpledynamicproxy { Public Static voidconsumer (MyInterface myinterface) {myinterface.dosomething (); Myinterface.somethingelse ("Bubu."); } Public Static voidMain (string[] args) {realobject realobject=NewRealobject (); Consumer (realobject); Print ("-----------------------------------------"); /*** 1. A class loader "You can usually get its classloader from a class object that has already been loaded, and then pass it to it" * 2. The list of interfaces that you want the proxy to implement is "not a class or abstract class" * 3. and Invocationhandle An implementation of R (a call processor)*/MyInterface Dynamicproxy= (MyInterface) proxy.newproxyinstance (MyInterface.class. getClassLoader (),NewClass[]{myinterface.class},NewDynamicproxyhandle (realobject)); Consumer (dynamicproxy); }}
Java-related static agent and dynamic agent implementation