1. Code
PackageCom.che.carcheck.ui.helper;ImportCom.che.carcheck.support.util.LogUtil;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;/** * Proxy Mode Learning * * Yu Tianhan on 16/5/6 pm * * Public class proxystudy { //Usage Scenarios Public Static void Main() {//By proxy classUserimpl Impl =NewUserimpl ("Xiao Ming"); Impl.login (); Impl.updateinfo ();//static proxyLogutil.print ("Static proxy: Start"); Userstaticproxy Staticproxy =NewUserstaticproxy (IMPL); Staticproxy.login (); Staticproxy.updateinfo ();//Dynamic AgentLogutil.print ("Dynamic agent: Start"); Userdynamicproxyfactory factory =NewUserdynamicproxyfactory (); User Dynamicproxy = (user) factory.createproxy (impl); Dynamicproxy.login (); Dynamicproxy.updateinfo (); }//Interface Public interface User { voidLogin ();voidUpdateInfo (); }//By proxy class Public Static class Userimpl implements User { PrivateString name; Public Userimpl(String name) { This. name = name; }@Override Public void Login() {Logutil.print ( This. Name +"Sign in ..."); }@Override Public void UpdateInfo() {Logutil.print ( This. Name +"Update information ..."); } }//static proxy Public Static class userstaticproxy implements User { PrivateUserimpl Countimpl; Public Userstaticproxy(Userimpl Countimpl) { This. Countimpl = Countimpl; }@Override Public void Login() {Dobefore (); Countimpl.login (); }@Override Public void UpdateInfo() {Dobefore (); Countimpl.updateinfo (); Doafter (); }Private void Dobefore() {Logutil.print ("Static proxy: Pre-action ..."); }Private void Doafter() {Logutil.print ("Static proxy: Post-action ..."); } }//jdk Dynamic Agent Public Static class userdynamicproxyfactory implements Invocationhandler { PrivateObject Target;//Bind the delegate object and return a proxy class PublicObjectCreateproxy(Object target) { This. target = target;//Get proxy object returnProxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), This);//To bind the interface (this is a flaw, cglib compensates for this flaw)}//Change the invocation logic of the method @Override PublicObjectInvoke(Object Proxy, Method method, object[] args)throwsthrowable {Object result =NULL;//Execution Method if(Method.getname (). Equals ("Login")) {Dobefore (); result = Method.invoke (target, args); }if(Method.getname (). Equals ("UpdateInfo")) {Dobefore (); result = Method.invoke (target, args); Doafter (); }returnResult }Private void Dobefore() {Logutil.print ("Dynamic proxy: Pre-action ..."); }Private void Doafter() {Logutil.print ("Dynamic proxy: Post-action ..."); } }}
2. Log
java-Dynamic Agent