1 16 package org.springframework.binding.method; 17 18 import java.lang.reflect.Method ; 19 20 import org.apache.commons.logging.Log; 21 import org.apache.commons.logging.LogFactory; 22 import org.springframework.binding.convert.ConversionService; 23 import org.springframework.binding.convert.support.DefaultConversionService; 24 import org.springframework.core.style.StylerUtils; 25 import org.springframework.util.CachingMapDecorator; 26 27 34 public class MethodInvoker { 35 36 protected static final Log logger = LogFactory.getLog(MethodInvoker.class); 37 38 42 private ConversionService conversionService = new DefaultConversionService(); 43 44 47 private CachingMapDecorator methodCache = new CachingMapDecorator(true) { 48 public Object create(Object key) { 49 return ((ClassMethodKey)key).getMethod(); 50 } 51 }; 52 53 56 public void setConversionService(ConversionService conversionService) { 57 this.conversionService = conversionService; 58 } 59 60 71 public Object invoke(MethodSignature signature, Object bean, Object argumentSource) 72 throws MethodInvocationException { 73 Parameters parameters = signature.getParameters(); 74 Object [] arguments = new Object [parameters.size()]; 75 for (int i = 0; i < parameters.size(); i++) { 76 Parameter parameter = parameters.getParameter(i); 77 Object argument = parameter.getName().evaluate(argumentSource, null); 78 arguments[i] = applyTypeConversion(argument, parameter.getType()); 79 } 80 Class [] parameterTypes = parameters.getTypesArray(); 81 for (int i = 0; i < parameterTypes.length; i++) { 82 if (parameterTypes[i] == null) { 83 Object argument = arguments[i]; 84 if (argument != null) { 85 parameterTypes[i] = argument.getClass(); 86 } 87 } 88 } 89 ClassMethodKey key = new ClassMethodKey(bean.getClass(), signature.getMethodName(), parameterTypes); 90 try { 91 Method method = (Method )methodCache.get(key); 92 if (logger.isDebugEnabled()) { 93 logger.debug("Invoking method with signature [" + key + "] with arguments " 94 + StylerUtils.style(arguments) + " on bean [" + bean + "]"); 95 96 } 97 Object returnValue = method.invoke(bean, arguments); 98 if (logger.isDebugEnabled()) { 99 logger.debug("Invoked method with signature [" + key + "]' returned value [" + returnValue + "]"); 100 } 101 return returnValue; 102 } 103 catch (Exception e) { 104 throw new MethodInvocationException(key, arguments, e); 105 } 106 } 107 108 115 protected Object applyTypeConversion(Object parameterValue, Class targetType) { 116 if (parameterValue == null || targetType == null) { 117 return parameterValue; 118 } 119 return conversionService.getConversionExecutor(parameterValue.getClass(), targetType).execute(parameterValue); 120 } 121 } | Popular Tags |