java動態(tài)代理源碼分析泼各,總結(jié)亏拉。
java動態(tài)代理實現(xiàn)步驟:
1逆巍、創(chuàng)建代理接口實例對象莽使,如HelloService helloService = new HelloServiceImpl();
2、實現(xiàn)接口InvocationHandler灵再;
3、通過Proxy創(chuàng)建代理對象翎迁,如HelloService helloServiceProxy = (HelloService) Proxy.newProxyInstance(helloService.getClass().getClassLoader(),
helloService.getClass().getInterfaces(), new HelloProxy(helloService));
helloServiceProxy.sayHello("hs", "spring");
通過閱讀源碼發(fā)現(xiàn)责嚷,動態(tài)生成代理對象$Proxy0掂铐,該對象繼承Proxy類
和實現(xiàn)HelloService接口,重寫了sayHello方法全陨,并在方法內(nèi)部調(diào)用了InvocationHandler實現(xiàn)類的invoke(...)方法,從而完成了動態(tài)代理的效果辱姨。