1 8 package org.picocontainer.defaults; 9 10 import org.picocontainer.PicoContainer; 11 import org.picocontainer.PicoIntrospectionException; 12 13 import java.io.Serializable ; 14 import java.lang.reflect.InvocationTargetException ; 15 import java.lang.reflect.Method ; 16 import java.util.ArrayList ; 17 import java.util.Collections ; 18 import java.util.Iterator ; 19 import java.util.List ; 20 21 22 29 public class MethodCallingVisitor extends TraversalCheckingVisitor implements Serializable { 30 31 private transient Method method; 33 private final Object [] arguments; 34 private final Class type; 35 private final boolean visitInInstantiationOrder; 36 private final List componentInstances; 37 38 48 public MethodCallingVisitor(Method method, Class ofType, Object [] arguments, boolean visitInInstantiationOrder) { 49 if (method == null) { 50 throw new NullPointerException (); 51 } 52 this.method = method; 53 this.arguments = arguments; 54 this.type = ofType; 55 this.visitInInstantiationOrder = visitInInstantiationOrder; 56 this.componentInstances = new ArrayList (); 57 } 58 59 68 public MethodCallingVisitor(Method method, Class ofType, Object [] arguments) { 69 this(method, ofType, arguments, true); 70 } 71 72 public Object traverse(Object node) { 73 componentInstances.clear(); 74 try { 75 super.traverse(node); 76 if (!visitInInstantiationOrder) { 77 Collections.reverse(componentInstances); 78 } 79 for (Iterator iterator = componentInstances.iterator(); iterator.hasNext();) { 80 invoke(iterator.next()); 81 } 82 } finally { 83 componentInstances.clear(); 84 } 85 return Void.TYPE; 86 } 87 88 public void visitContainer(PicoContainer pico) { 89 super.visitContainer(pico); 90 componentInstances.addAll(pico.getComponentInstancesOfType(type)); 91 } 92 93 protected Method getMethod() { 94 return method; 95 } 96 97 protected Object [] getArguments() { 98 return arguments; 99 } 100 101 protected void invoke(final Object [] targets) { 102 for (int i = 0; i < targets.length; i++) { 103 invoke(targets[i]); 104 } 105 } 106 107 protected Object invoke(final Object target) { 108 final Method method = getMethod(); 109 try { 110 method.invoke(target, getArguments()); 111 } catch (IllegalArgumentException e) { 112 throw new PicoIntrospectionException("Can't call " + method.getName() + " on " + target, e); 113 } catch (IllegalAccessException e) { 114 throw new PicoIntrospectionException("Can't call " + method.getName() + " on " + target, e); 115 } catch (InvocationTargetException e) { 116 throw new PicoIntrospectionException("Failed when calling " + method.getName() + " on " + target, e 117 .getTargetException()); 118 } 119 return Void.TYPE; 120 } 121 } 122 | Popular Tags |