1 8 package org.picocontainer.gems.lifecycle; 9 10 import org.picocontainer.ComponentMonitor; 11 import org.picocontainer.defaults.AbstractMonitoringLifecycleStrategy; 12 13 import java.lang.reflect.InvocationTargetException ; 14 import java.lang.reflect.Method ; 15 import java.util.HashMap ; 16 import java.util.Map ; 17 18 19 31 public class ReflectionLifecycleStrategy extends AbstractMonitoringLifecycleStrategy { 32 33 private final static int START = 0; 34 private final static int STOP = 1; 35 private final static int DISPOSE = 2; 36 private String [] methodNames; 37 private final transient Map methodMap = new HashMap (); 38 39 45 public ReflectionLifecycleStrategy(ComponentMonitor monitor) { 46 this(monitor, "start", "stop", "dispose"); 47 } 48 49 59 public ReflectionLifecycleStrategy( 60 ComponentMonitor monitor, String startMethodName, String stopMethodName, 61 String disposeMethodName) { 62 super(monitor); 63 methodNames = new String []{startMethodName, stopMethodName, disposeMethodName}; 64 } 65 66 public void start(Object component) { 67 Method [] methods = init(component.getClass()); 68 invokeMethod(component, methods[START]); 69 } 70 71 public void stop(Object component) { 72 Method [] methods = init(component.getClass()); 73 invokeMethod(component, methods[STOP]); 74 } 75 76 public void dispose(Object component) { 77 Method [] methods = init(component.getClass()); 78 invokeMethod(component, methods[DISPOSE]); 79 } 80 81 private void invokeMethod(Object component, Method method) { 82 if (component != null && method != null) { 83 try { 84 long str = System.currentTimeMillis(); 85 currentMonitor().invoking(method, component); 86 method.invoke(component, new Object [0]); 87 currentMonitor().invoked(method, component, System.currentTimeMillis() - str); 88 } catch (IllegalAccessException e) { 89 RuntimeException re = new ReflectionLifecycleException(method.getName(), e); 90 currentMonitor().lifecycleInvocationFailed(method, component, re); 91 throw re; 92 } catch (InvocationTargetException e) { 93 RuntimeException re = new ReflectionLifecycleException(method.getName(), e); 94 currentMonitor().lifecycleInvocationFailed(method, component, re); 95 throw re; 96 } 97 } 98 } 99 100 103 public boolean hasLifecycle(Class type) { 104 Method [] methods = init(type); 105 for (int i = 0; i < methods.length; i++) { 106 if (methods[i] != null) { 107 return true; 108 } 109 } 110 return false; 111 } 112 113 private Method [] init(Class type) { 114 Method [] methods; 115 synchronized (methodMap) { 116 methods = (Method [])methodMap.get(type); 117 if (methods == null) { 118 methods = new Method [methodNames.length]; 119 for (int i = 0; i < methods.length; i++) { 120 try { 121 methods[i] = type.getMethod(methodNames[i], new Class [0]); 122 } catch (NoSuchMethodException e) { 123 continue; 124 } 125 } 126 methodMap.put(type, methods); 127 } 128 } 129 return methods; 130 } 131 } 132 | Popular Tags |