KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > acceptance > objects > SampleDynamicProxy


1 package com.thoughtworks.acceptance.objects;
2
3 import java.lang.reflect.InvocationHandler JavaDoc;
4 import java.lang.reflect.Method JavaDoc;
5 import java.lang.reflect.Proxy JavaDoc;
6
7 public class SampleDynamicProxy implements InvocationHandler JavaDoc {
8
9     private String JavaDoc aField = "hello";
10
11     public static interface InterfaceOne {
12         String JavaDoc doSomething();
13     }
14
15     public static interface InterfaceTwo {
16         String JavaDoc doSomething();
17     }
18
19     public static Object JavaDoc newInstance() {
20         return Proxy.newProxyInstance(InterfaceOne.class.getClassLoader(),
21                 new Class JavaDoc[]{InterfaceOne.class, InterfaceTwo.class},
22                 new SampleDynamicProxy());
23     }
24
25     public Object JavaDoc invoke(Object JavaDoc proxy, Method JavaDoc method, Object JavaDoc[] args) throws Throwable JavaDoc {
26         if (method.getName().equals("equals")) {
27             return equals(args[0]) ? Boolean.TRUE : Boolean.FALSE;
28         } else {
29             return aField;
30         }
31     }
32
33     public boolean equals(Object JavaDoc obj) {
34         return equalsInterfaceOne(obj) && equalsInterfaceTwo(obj);
35     }
36
37     private boolean equalsInterfaceOne(Object JavaDoc o) {
38         if (o instanceof InterfaceOne) {
39             InterfaceOne interfaceOne = (InterfaceOne) o;
40             return aField.equals(interfaceOne.doSomething());
41         } else {
42             return false;
43         }
44     }
45
46     private boolean equalsInterfaceTwo(Object JavaDoc o) {
47         if (o instanceof InterfaceTwo) {
48             InterfaceTwo interfaceTwo = (InterfaceTwo) o;
49             return aField.equals(interfaceTwo.doSomething());
50         } else {
51             return false;
52         }
53     }
54
55 }
56
Popular Tags