1 8 14 package jfun.yan; 15 16 import jfun.util.Misc; 17 import jfun.yan.function.Function; 18 import jfun.yan.util.Utils; 19 20 21 27 final class FunctionComponent<T> extends Component<T>{ 28 private final Function<T> fun; 29 private final Class [] param_types; 30 FunctionComponent(final Function<T> fun) { 31 this.fun = fun; 32 this.param_types = getParameterTypes(fun); 33 } 34 private static Class [] getParameterTypes(Function fun){ 35 final Class [] result = fun.getParameterTypes(); 36 if(result==null || result.length==0) 37 return null; 38 else return result; 39 } 40 private Object [] getArgs(Dependency dep){ 41 if(param_types==null){ 42 return Misc.array0; 43 } 44 final Object [] args = new Object [param_types.length]; 45 for(int i=0; i<param_types.length; i++){ 46 final Class param_type = param_types[i]; 47 try{ 48 args[i] = dep.getArgument(fun, i, param_type); 49 } 50 catch(DefaultingException e){ 51 args[i] = null; 53 } 54 catch(YanException e){ 55 e.push(new ParameterEntry(fun, i)); 56 throw e; 57 } 58 } 59 return args; 60 } 61 public T create(Dependency dep) { 62 final Object [] args = getArgs(dep); 63 try{ 64 try{ 65 return fun.call(args); 66 } 67 catch(Throwable e){ 68 throw Utils.wrapInstantiationException(e); 69 } 70 } 71 catch(YanException e){ 72 e.push(fun); 73 throw e; 74 } 75 } 76 77 public Class <T> getType() { 78 return fun.getReturnType(); 79 } 80 public boolean isConcrete(){ 81 return fun.isConcrete(); 82 } 83 public Class <T> verify(Dependency ac) { 84 final Class [] params = fun.getParameterTypes(); 85 for(int i=0; i<params.length; i++){ 86 final Class param_type = params[i]; 87 try{ 88 ac.verifyArgument(fun, i, param_type); 89 } 90 catch(DefaultingException e){ 91 continue; 92 } 93 catch(YanException e){ 94 e.push(new ParameterEntry(fun, i)); 95 throw e; 96 } 97 } 98 return fun.getReturnType(); 99 } 100 101 public boolean equals(Object other) { 102 if(other instanceof FunctionComponent){ 103 final FunctionComponent cf2 = (FunctionComponent)other; 104 return fun.equals(cf2.fun); 105 } 106 else return fun.equals(other); 107 } 108 public int hashCode() { 109 return fun.hashCode(); 110 } 111 public String toString() { 112 return fun.toString(); 113 } 114 public boolean isSingleton(){ 115 return false; 116 } 117 } 118 | Popular Tags |