1 4 package com.tc.common.proxy; 5 6 import com.tc.logging.TCLogger; 7 import com.tc.logging.TCLogging; 8 import com.tc.util.Assert; 9 10 import java.lang.reflect.InvocationHandler ; 11 import java.lang.reflect.InvocationTargetException ; 12 import java.lang.reflect.Method ; 13 import java.lang.reflect.Proxy ; 14 15 25 class GenericInvocationHandler implements InvocationHandler { 26 private static final TCLogger logger = TCLogging.getLogger(GenericInvocationHandler.class); 27 28 private Object handler; 29 30 33 protected GenericInvocationHandler() { 34 this.handler = null; 35 } 36 37 public GenericInvocationHandler(Object handler) { 38 Assert.eval(handler != null); 39 this.handler = handler; 40 } 41 42 public Object invoke(Object proxy, Method method, Object [] args) throws Throwable { 43 try { 44 return invokeInternal(proxy, method, args); 45 } catch (Throwable t) { 46 try { 49 if (logger.isDebugEnabled()) { 50 logger.debug("EXCEPTION thrown trying to call " + method, t); 51 } 52 } catch (Throwable loggingError) { 53 } 55 56 throw t; 57 } 58 } 59 60 protected Object getHandler() { 61 return this.handler; 62 } 63 64 protected void setHandler(Object o) { 65 this.handler = o; 66 } 67 68 private Object invokeInternal(Object proxy, Method method, Object [] args) throws Throwable { 69 try { 70 final Method theMethod = handler.getClass().getMethod(method.getName(), method.getParameterTypes()); 71 try { 72 theMethod.setAccessible(true); 73 } catch (SecurityException se) { 74 logger.warn("Cannot setAccessible(true) for method [" + theMethod + "], " + se.getMessage()); 75 } 76 return theMethod.invoke(handler, args); 77 } catch (InvocationTargetException ite) { 78 throw ite.getCause(); 84 } catch (NoSuchMethodException nsme) { 85 return handlerMethodNotFound(proxy, method, args); 86 } 87 } 88 89 private String describeClasses(Class [] classes) { 90 StringBuffer out = new StringBuffer (); 91 for (int i = 0; i < classes.length; ++i) { 92 if (i > 0) out.append(", "); 93 out.append(classes[i].getName()); 94 } 95 return out.toString(); 96 } 97 98 protected Object handlerMethodNotFound(Object proxy, Method method, Object [] args) throws Throwable { 99 throw new NoSuchMethodError ("Handler " + handler + " does not have a method named " + method.getName() 100 + " that is " + "has argument types " + describeClasses(method.getParameterTypes())); 101 } 102 103 } | Popular Tags |