1 4 package com.tc.common.proxy; 5 6 import java.lang.reflect.InvocationHandler ; 7 import java.lang.reflect.InvocationTargetException ; 8 import java.lang.reflect.Method ; 9 import java.lang.reflect.Proxy ; 10 11 14 public class MethodMonitorProxy { 15 public static Object createProxy(final Object objectToMonitor, MethodInvocationEventListener listener) { 16 return createProxy(objectToMonitor, new MethodInvocationEventListener[] { listener }); 17 } 18 19 public static Object createProxy(final Object objectToMonitor, MethodInvocationEventListener listeners[]) { 20 if (null == objectToMonitor) { throw new NullPointerException ("Cannot proxy a null instance"); } 21 if (null == listeners) { throw new NullPointerException ("Listener list cannot be null"); } 22 23 for (int i = 0; i < listeners.length; i++) { 24 if (null == listeners[i]) { throw new NullPointerException ("Null listener in list at position " + i); } 25 } 26 27 final Class clazz = objectToMonitor.getClass(); 28 final Class [] interfaces = clazz.getInterfaces(); 29 30 if (0 == interfaces.length) { throw new IllegalArgumentException ("Class (" + clazz.getName() 31 + ") does not implement any interfaces"); } 32 33 return Proxy.newProxyInstance(clazz.getClassLoader(), interfaces, new MonitorHandler(objectToMonitor, listeners)); 34 } 35 36 private static class MonitorHandler implements InvocationHandler { 37 private final MethodInvocationEventListener[] listeners; 38 private final Object delegate; 39 40 MonitorHandler(Object delegate, MethodInvocationEventListener[] listeners) { 41 this.listeners = (MethodInvocationEventListener[]) listeners.clone(); 42 this.delegate = delegate; 43 } 44 45 public Object invoke(Object proxy, Method method, Object [] args) throws Throwable { 46 Throwable exception = null; 47 48 Object returnValue = null; 49 50 final long end; 51 final long start = System.currentTimeMillis(); 52 try { 53 returnValue = method.invoke(delegate, args); 54 } catch (InvocationTargetException ite) { 55 exception = ite.getCause(); 56 } finally { 57 end = System.currentTimeMillis(); 58 } 59 60 final MethodInvocationEvent event = new MethodInvocationEventImpl(start, end, delegate, method, args, exception, 61 returnValue); 62 for (int i = 0; i < listeners.length; i++) { 63 listeners[i].methodInvoked(event); 64 } 65 66 if (null != exception) { 67 throw exception; 68 } else { 69 return returnValue; 70 } 71 } 72 } 73 } | Popular Tags |