1 6 package org.jfox.ioc.factory; 7 8 import java.lang.reflect.InvocationTargetException ; 9 import java.lang.reflect.Method ; 10 import java.util.Arrays ; 11 12 import org.jfox.ioc.Component; 13 import org.jfox.ioc.ComponentContext; 14 import org.jfox.ioc.depend.Dependency; 15 import org.jfox.ioc.depend.DependencyPack; 16 import org.jfox.ioc.exception.ComponentException; 17 import org.jfox.ioc.util.Classes; 18 19 27 28 public class PropertyComponentFactory extends DecorateComponentFactory { 29 private DependencyPack[] paramPacks; 30 31 34 private DependencyPack[] tempParamPacks = DependencyPack.EMPTY_PARAMETER_PACKS; 35 36 public PropertyComponentFactory(ConstrComponentFactory delegate, DependencyPack[] propParamPacks) { 37 super(delegate); 38 this.paramPacks = propParamPacks; 39 } 40 41 44 public synchronized Component makeComponent() throws ComponentException { 45 Component component = super.makeComponent(); 46 doMethods(component); 47 return component; 48 } 49 50 56 public synchronized Component makeComponent(ComponentContext context) throws ComponentException { 57 Component component = super.makeComponent(); 58 component.setComponentContext(context); 59 doMethods(component); 60 return component; 61 } 62 63 66 public DependencyPack[] getParameterPacks() { 67 return paramPacks; 68 } 69 70 75 public void addParameterPack(DependencyPack[] propParamPacks) { 76 if(propParamPacks != null && propParamPacks.length != 0) { 77 tempParamPacks = propParamPacks; 78 } 79 } 80 81 87 private void doMethods(Component component) throws ComponentException { 88 if(paramPacks == null || paramPacks.length == 0) return; 89 for(int i = 0; i < paramPacks.length; i++) { 90 DependencyPack pack = paramPacks[i]; 91 doMethod(component, pack); 92 } 93 94 if(tempParamPacks != null && tempParamPacks.length != 0) { 95 try { 96 97 for(int i = 0; i < tempParamPacks.length; i++) { 98 DependencyPack pack = tempParamPacks[i]; 99 doMethod(component, pack); 100 } 101 102 } 103 finally { 104 tempParamPacks = DependencyPack.EMPTY_PARAMETER_PACKS; 105 } 106 } 107 } 108 109 112 protected void doMethod(Component component, DependencyPack pack) throws ComponentException { 113 Object [] params = resolveParameters(new Dependency[]{pack.getParameter()}); 114 Class [] types = getParameterTypes(new Dependency[]{pack.getParameter()}); 115 116 117 Method method = null; 118 try { 119 method = Classes.getMethod(component.getClass(), pack.getName(), types); 120 } 121 catch(Exception e) { 122 throw new ComponentException("get method " + pack.getName() + Arrays.asList(types) + " error", e); 123 } 124 try { 125 method.invoke(component, params); 126 } 127 catch(InvocationTargetException e) { 128 throw new ComponentException("do method " + pack.getName() + " error", e.getTargetException()); 129 } 130 catch(Exception e) { 131 throw new ComponentException("do method " + pack.getName() + " error", e); 132 } 133 } 134 135 public static void main(String [] args) { 136 137 } 138 } 139 140 | Popular Tags |