Riordon

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
 1 package DynamicProxy;
 2 
 3 import java.lang.reflect.InvocationHandler;
 4 import java.lang.reflect.Method;
 5 import java.lang.reflect.Proxy;
 6 
 7 interface AbstractClass {
 8     public void show();
 9 }
10 
11 class ClassA implements AbstractClass {
12     public void show() {
13         System.out.println("I am A !");
14     }
15 }
16 
17 class ClassB implements AbstractClass {
18     public void show() {
19         System.out.println("I am B !");
20     }
21 }
22 
23 class Invoker implements InvocationHandler {
24     AbstractClass ac;
25     public Invoker(AbstractClass ac) {
26         this.ac = ac;
27     }
28     
29     @Override
30     public Object invoke(Object proxy, Method method, Object[] args)
31             throws Throwable {
32         method.invoke(ac, args);
33         return null;
34     }
35     
36 }
37 
38 public class DynamicProxyTest {
39     public static void main(String[] args) {
40         
41         Invoker invoker1 = new Invoker(new ClassA());
42         AbstractClass ac1 = (AbstractClass) Proxy.newProxyInstance(AbstractClass.class.getClassLoader(), new Class[] {AbstractClass.class}, invoker1);
43         ac1.show();
44         
45         Invoker invoker2 = new Invoker(new ClassB());
46         AbstractClass ac2 = (AbstractClass) Proxy.newProxyInstance(AbstractClass.class.getClassLoader(), new Class[] {AbstractClass.class}, invoker2);
47         ac2.show();
48     }
49 }

 

posted on 2014-10-11 09:32  Riordon  阅读(137)  评论(0编辑  收藏  举报