KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > easymock > internal > ObjectMethodsFilter


1 /*
2  * Copyright (c) 2001-2005 OFFIS. This program is made available under the terms of
3  * the MIT License.
4  */

5 package org.easymock.internal;
6
7 import java.lang.reflect.InvocationHandler JavaDoc;
8 import java.lang.reflect.Method JavaDoc;
9
10 public class ObjectMethodsFilter implements InvocationHandler JavaDoc {
11     private Method JavaDoc equalsMethod;
12
13     private Method JavaDoc hashCodeMethod;
14
15     private Method JavaDoc toStringMethod;
16
17     private InvocationHandler JavaDoc delegate;
18
19     public ObjectMethodsFilter(InvocationHandler JavaDoc delegate) {
20         try {
21             equalsMethod = Object JavaDoc.class.getMethod("equals",
22                     new Class JavaDoc[] { Object JavaDoc.class });
23             hashCodeMethod = Object JavaDoc.class.getMethod("hashCode", (Class JavaDoc[]) null);
24             toStringMethod = Object JavaDoc.class.getMethod("toString", (Class JavaDoc[]) null);
25         } catch (NoSuchMethodException JavaDoc e) {
26             // ///CLOVER:OFF
27
throw new RuntimeException JavaDoc("An Object method could not be found!");
28             // ///CLOVER:ON
29
}
30         this.delegate = delegate;
31     }
32
33     public final Object JavaDoc invoke(Object JavaDoc proxy, Method JavaDoc method, Object JavaDoc[] args)
34             throws Throwable JavaDoc {
35         if (equalsMethod.equals(method)) {
36             return proxy == args[0] ? Boolean.TRUE : Boolean.FALSE;
37         }
38         if (hashCodeMethod.equals(method)) {
39             return new Integer JavaDoc(System.identityHashCode(proxy));
40         }
41         if (toStringMethod.equals(method)) {
42             return mockToString(proxy);
43         }
44         return delegate.invoke(proxy, method, args);
45     }
46
47     private String JavaDoc mockToString(Object JavaDoc proxy) {
48         return "EasyMock for " + mockedInterface(proxy);
49     }
50
51     private String JavaDoc mockedInterface(Object JavaDoc proxy) {
52         Class JavaDoc[] interfaces = proxy.getClass().getInterfaces();
53         return interfaces.length > 0 ? interfaces[0].toString() : proxy
54                 .getClass().getSuperclass().toString();
55     }
56 }
Popular Tags