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