<!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"/@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.5pt; mso-bidi-font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体; mso-font-kerning:1.0pt;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:612.0pt 792.0pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:36.0pt; mso-footer-margin:36.0pt; mso-paper-source:0;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:256713394; mso-list-template-ids:-1699456634;} @list l1 {mso-list-id:292448747; mso-list-template-ids:1567683388;} @list l2 {mso-list-id:1199665814; mso-list-template-ids:1173917332;} @list l3 {mso-list-id:1333723713; mso-list-template-ids:1064840542;} @list l4 {mso-list-id:2066417278; mso-list-template-ids:-1552372328;} ol {margin-bottom:0cm;} ul {margin-bottom:0cm;} -->
实现动态代理:
真实的接口:
Java 代码
- public interface Hello {
- void sayHello(String to);
- void print(String p);
- }
它的真实实现类:
Java 代码
- public class HelloImpl implements Hello {
- public void sayHello(String to) {
- System.out.println("Say hello to " + to);
- }
- public void print(String s) {
- System.out.println("print : " + s);
- }
- }
在这里生成与代理类相关联的InvocationHandler 对象
Java 代码
- public class LogHandler implements InvocationHandler {
- private Object dele;
- public LogHandler(Object obj) {
- this.dele = obj;
- }
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- doBefore();
- // 在这里完全可以把下面这句注释掉,而做一些其它的事情
- Object result = method.invoke(dele, args);
- after();
- return result;
- }
- private void doBefore() {
- System.out.println("before....");
- }
- private void after() {
- System.out.println("after....");
- }
- }
最后是测试类:
Java 代码
- public class ProxyTest {
- public static void main(String[] args) {
- HelloImpl impl = new HelloImpl();
- LogHandler handler = new LogHandler(impl);
- // 这里把handler 与impl 新生成的代理类相关联
- Hello hello = (Hello) Proxy.newProxyInstance(impl.getClass().getClassLoader(), impl.getClass().getInterfaces(), handler);
- // 这里无论访问哪个方法,都是会把请求转发到handler.invoke
- hello.print("All the test");
- hello.sayHello("Denny");
- }
- }
这里是输出结果:
Java 代码
- before....
- print : All the test
- after....
- before....
- Say hello to Denny
- after....