1 9 package org.jboss.portal.common.junit; 10 11 import java.lang.reflect.Proxy ; 12 import java.lang.reflect.InvocationHandler ; 13 import java.lang.reflect.Method ; 14 import java.lang.reflect.InvocationTargetException ; 15 16 22 public class MockFactory 23 { 24 25 public static Object wrap(ClassLoader loader, Class [] itfs, Object implementation) throws IllegalArgumentException 26 { 27 if (implementation == null) 28 { 29 throw new IllegalArgumentException ("Implementation cannot be null"); 30 } 31 InvocationHandler handler = new MockHandler(implementation); 32 Object proxy = Proxy.newProxyInstance(loader, itfs, handler); 33 return proxy; 34 } 35 36 private static class MockHandler implements InvocationHandler 37 { 38 39 private final Object target; 40 41 public MockHandler(Object target) 42 { 43 this.target = target; 44 } 45 46 public Object invoke(Object proxy, Method proxyMethod, Object [] args) throws Throwable 47 { 48 Method targetMethod = target.getClass().getMethod(proxyMethod.getName(), proxyMethod.getParameterTypes()); 50 51 if (targetMethod == null) 53 { 54 targetMethod = target.getClass().getMethod("invoke", new Class []{Object [].class}); 56 57 if (targetMethod != null) 59 { 60 args = new Object []{args}; 61 } 62 } 63 64 if (targetMethod == null) 66 { 67 throw new UnsupportedOperationException ("Method " + proxyMethod + " was not found"); 68 } 69 70 try 72 { 73 return targetMethod.invoke(target, args); 74 } 75 catch (Exception e) 76 { 77 if (e instanceof InvocationTargetException ) 78 { 79 InvocationTargetException ite = (InvocationTargetException )e; 80 Throwable cause = ite.getCause(); 81 throw cause; 82 } 83 else 84 { 85 UnsupportedOperationException ex = new UnsupportedOperationException ("Method " + proxyMethod + " threw an unexpected exception"); 86 ex.initCause(e); 87 throw ex; 88 } 89 } 90 } 91 } 92 } 93 | Popular Tags |