1 16 package org.apache.commons.betwixt.expression; 17 18 import java.lang.reflect.Array ; 19 import java.lang.reflect.Method ; 20 import java.util.Collection ; 21 22 import org.apache.commons.logging.Log; 23 import org.apache.commons.logging.LogFactory; 24 25 32 public class MethodUpdater implements Updater { 33 34 35 private static Log log = LogFactory.getLog( MethodUpdater.class ); 36 37 41 public static void setLog( Log aLog ) { 42 log = aLog; 43 } 44 45 46 private Method method; 47 48 private Class valueType; 49 50 51 public MethodUpdater() { 52 } 53 54 58 public MethodUpdater(Method method) { 59 setMethod( method ); 60 } 61 62 67 public void update(Context context, Object newValue) { 68 Object bean = context.getBean(); 69 if ( bean != null ) { 70 if ( newValue instanceof String ) { 71 if ( log.isTraceEnabled() ) { 73 log.trace("Converting primitive to " + valueType); 74 } 75 newValue = context.getObjectStringConverter() 76 .stringToObject( (String ) newValue, valueType, null, context ); 77 } 78 if ( newValue != null ) { 79 91 } 92 if (newValue instanceof Collection && valueType.isArray()) { 94 Collection valuesAsCollection = (Collection ) newValue; 95 Class componentType = valueType.getComponentType(); 96 if (componentType != null) { 97 Object [] valuesAsArray = 98 (Object []) Array.newInstance(componentType, valuesAsCollection.size()); 99 newValue = valuesAsCollection.toArray(valuesAsArray); 100 } 101 } 102 103 Object [] arguments = { newValue }; 104 try { 105 if ( log.isDebugEnabled() ) { 106 log.debug( 107 "Calling setter method: " + method.getName() + " on bean: " + bean 108 + " with new value: " + newValue 109 ); 110 } 111 method.invoke( bean, arguments ); 112 113 } catch (Exception e) { 114 String valueTypeName = (newValue != null) ? newValue.getClass().getName() : "null"; 115 log.warn( 116 "Cannot evaluate method: " + method.getName() + " on bean: " + bean 117 + " of type: " + bean.getClass().getName() + " with value: " + newValue 118 + " of type: " + valueTypeName 119 ); 120 handleException(context, e); 121 } 122 } 123 } 124 125 130 public Method getMethod() { 131 return method; 132 } 133 134 138 public void setMethod(Method method) { 139 this.method = method; 140 Class [] types = method.getParameterTypes(); 141 if ( types == null || types.length <= 0 ) { 142 throw new IllegalArgumentException ( "The Method must have at least one parameter" ); 143 } 144 this.valueType = types[0]; 145 } 146 147 150 155 protected void handleException(Context context, Exception e) { 156 log.info( "Caught exception: " + e, e ); 157 } 158 159 163 public String toString() { 164 return "MethodUpdater [method=" + method + "]"; 165 } 166 } 167 | Popular Tags |