ReflectionHelper.java 15.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * Copyright 2002-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.expression.spel.support;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import org.springframework.expression.EvaluationException;
import org.springframework.expression.TypeConverter;
25
import org.springframework.expression.spel.SpelEvaluationException;
26
import org.springframework.expression.spel.SpelMessage;
27
import org.springframework.util.Assert;
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
import org.springframework.util.ClassUtils;

/**
 * Utility methods used by the reflection resolver code to discover the appropriae
 * methods/constructors and fields that should be used in expressions.
 *
 * @author Andy Clement
 * @author Juergen Hoeller
 * @since 3.0
 */
public class ReflectionHelper {

	/**
	 * Compare argument arrays and return information about whether they match. A supplied type converter and
	 * conversionAllowed flag allow for matches to take into account that a type may be transformed into a different
	 * type by the converter.
	 * @param expectedArgTypes the array of types the method/constructor is expecting
	 * @param suppliedArgTypes the array of types that are being supplied at the point of invocation
	 * @param typeConverter a registered type converter
	 * @return a MatchInfo object indicating what kind of match it was or null if it was not a match
	 */
49
	public static ArgumentsMatchInfo compareArguments( 
50 51
			Class[] expectedArgTypes, Class[] suppliedArgTypes, TypeConverter typeConverter) {

52 53
		Assert.isTrue(expectedArgTypes.length==suppliedArgTypes.length, "Expected argument types and supplied argument types should be arrays of same length");

54 55 56 57 58 59 60 61 62 63
		ArgsMatchKind match = ArgsMatchKind.EXACT;
		List<Integer> argsRequiringConversion = null;
		for (int i = 0; i < expectedArgTypes.length && match != null; i++) {
			Class suppliedArg = suppliedArgTypes[i];
			Class expectedArg = expectedArgTypes[i];
			if (expectedArg != suppliedArg) {
				if (ClassUtils.isAssignable(expectedArg, suppliedArg)
				/* || isWidenableTo(expectedArg, suppliedArg) */) {
					if (match != ArgsMatchKind.REQUIRES_CONVERSION) {
						match = ArgsMatchKind.CLOSE;
64
					} 
65 66 67 68 69 70 71 72 73 74 75 76 77
				} else if (typeConverter.canConvert(suppliedArg, expectedArg)) {
					if (argsRequiringConversion == null) {
						argsRequiringConversion = new ArrayList<Integer>();
					}
					argsRequiringConversion.add(i);
					match = ArgsMatchKind.REQUIRES_CONVERSION;
				} else {
					match = null;
				}
			}
		}
		if (match == null) {
			return null;
78
		} else {
79 80 81 82 83 84
			if (match == ArgsMatchKind.REQUIRES_CONVERSION) {
				int[] argsArray = new int[argsRequiringConversion.size()];
				for (int i = 0; i < argsRequiringConversion.size(); i++) {
					argsArray[i] = argsRequiringConversion.get(i);
				}
				return new ArgumentsMatchInfo(match, argsArray);
85
			} else {
86 87 88 89 90 91 92 93
				return new ArgumentsMatchInfo(match);
			}
		}
	}

	/**
	 * Compare argument arrays and return information about whether they match. A supplied type converter and
	 * conversionAllowed flag allow for matches to take into account that a type may be transformed into a different
94
	 * type by the converter. This variant of compareArguments also allows for a varargs match.
95 96
	 * @param expectedArgTypes the array of types the method/constructor is expecting
	 * @param suppliedArgTypes the array of types that are being supplied at the point of invocation
97
	 * @param typeConverter a registered type converter 
98 99
	 * @return a MatchInfo object indicating what kind of match it was or null if it was not a match
	 */
100
	public static ArgumentsMatchInfo compareArgumentsVarargs(
101
			Class[] expectedArgTypes, Class[] suppliedArgTypes, TypeConverter typeConverter) {
102
 
103 104 105
		Assert.isTrue(expectedArgTypes!=null && expectedArgTypes.length>0, "Expected arguments must at least include one array (the vargargs parameter)");
		Assert.isTrue(expectedArgTypes[expectedArgTypes.length-1].isArray(), "Final expected argument should be array type (the varargs parameter)");
		
106 107 108 109 110
		ArgsMatchKind match = ArgsMatchKind.EXACT;
		List<Integer> argsRequiringConversion = null;

		// Check up until the varargs argument:

111 112 113
		// Deal with the arguments up to 'expected number' - 1 (that is everything but the varargs argument)
		int argCountUpToVarargs = expectedArgTypes.length-1;
		for (int i = 0; i < argCountUpToVarargs && match != null; i++) {
114
			Class suppliedArg = suppliedArgTypes[i];
115
			Class<?> expectedArg = expectedArgTypes[i];
116 117 118 119 120
			if (expectedArg != suppliedArg) {
				if (expectedArg.isAssignableFrom(suppliedArg) || ClassUtils.isAssignableValue(expectedArg, suppliedArg)) {
					if (match != ArgsMatchKind.REQUIRES_CONVERSION) {
						match = ArgsMatchKind.CLOSE;
					}
121
				} else if (typeConverter.canConvert(suppliedArg, expectedArg)) {
122 123 124 125 126 127 128 129 130 131
					if (argsRequiringConversion == null) {
						argsRequiringConversion = new ArrayList<Integer>();
					}
					argsRequiringConversion.add(i);
					match = ArgsMatchKind.REQUIRES_CONVERSION;
				} else {
					match = null;
				}
			}
		}
132
		// If already confirmed it cannot be a match, then returnW
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
		if (match == null) {
			return null;
		}

		// Special case: there is one parameter left and it is an array and it matches the varargs expected argument -
		// that is a match, the caller has already built the array
		if (suppliedArgTypes.length == expectedArgTypes.length
				&& expectedArgTypes[expectedArgTypes.length - 1] == suppliedArgTypes[suppliedArgTypes.length - 1]) {
		} else {
			// Now... we have the final argument in the method we are checking as a match and we have 0 or more other
			// arguments left to pass to it.
			Class varargsParameterType = expectedArgTypes[expectedArgTypes.length - 1].getComponentType();

			// All remaining parameters must be of this type or convertable to this type
			for (int i = expectedArgTypes.length - 1; i < suppliedArgTypes.length; i++) {
				Class suppliedArg = suppliedArgTypes[i];
				if (varargsParameterType != suppliedArg) {
					if (ClassUtils.isAssignable(varargsParameterType, suppliedArg)) {
						if (match != ArgsMatchKind.REQUIRES_CONVERSION) {
							match = ArgsMatchKind.CLOSE;
						}
154
					} else if (typeConverter.canConvert(suppliedArg, varargsParameterType)) {
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
						if (argsRequiringConversion == null) {
							argsRequiringConversion = new ArrayList<Integer>();
						}
						argsRequiringConversion.add(i);
						match = ArgsMatchKind.REQUIRES_CONVERSION;
					}
					else {
						match = null;
					}
				}
			}
		}

		if (match == null) {
			return null;
		}
		else {
			if (match == ArgsMatchKind.REQUIRES_CONVERSION) {
				int[] argsArray = new int[argsRequiringConversion.size()];
				for (int i = 0; i < argsRequiringConversion.size(); i++) {
					argsArray[i] = argsRequiringConversion.get(i);
				}
				return new ArgumentsMatchInfo(match, argsArray);
			}
			else {
				return new ArgumentsMatchInfo(match);
			}
		}
	}

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
	/**
	 * Takes an input set of argument values and, following the positions specified in the int array, it converts
	 * them to the types specified as the required parameter types.  The arguments are converted 'in-place' in the
	 * input array.
	 * @param requiredParameterTypes the types that the caller would like to have
	 * @param isVarargs whether the requiredParameterTypes is a varargs list
	 * @param converter the type converter to use for attempting conversions
	 * @param argumentsRequiringConversion details which of the input arguments need conversion
	 * @param arguments the actual arguments that need conversion
	 * @throws EvaluationException if a problem occurs during conversion
	 */
	public static void convertArguments(Class[] requiredParameterTypes, boolean isVarargs, TypeConverter converter,
			int[] argumentsRequiringConversion, Object[] arguments) throws EvaluationException {
		 
		Assert.notNull(argumentsRequiringConversion,"should not be called if no conversions required");
		Assert.notNull(arguments,"should not be called if no conversions required");
		
202 203
		Class varargsType = null;
		if (isVarargs) {
204 205
			Assert.isTrue(requiredParameterTypes[requiredParameterTypes.length-1].isArray(),"if varargs then last parameter type must be array");
			varargsType = requiredParameterTypes[requiredParameterTypes.length - 1].getComponentType();
206
		}
207
		for (Integer argPosition : argumentsRequiringConversion) {
208
			Class<?> targetType = null;
209
			if (isVarargs && argPosition >= (requiredParameterTypes.length - 1)) {
210
				targetType = varargsType;
211 212
			} else {
				targetType = requiredParameterTypes[argPosition];
213 214 215 216 217
			}
			arguments[argPosition] = converter.convertValue(arguments[argPosition], targetType);
		}
	}

218 219 220 221 222 223 224 225 226 227 228
	/**
	 * Convert a supplied set of arguments into the requested types.  If the parameterTypes are related to 
	 * a varargs method then the final entry in the parameterTypes array is going to be an array itself whose
	 * component type should be used as the conversion target for extraneous arguments. (For example, if the
	 * parameterTypes are {Integer, String[]} and the input arguments are {Integer, boolean, float} then both
	 * the boolean and float must be converted to strings).  This method does not repackage the arguments
	 * into a form suitable for the varargs invocation
	 * @param parameterTypes the types to be converted to
	 * @param isVarargs whether parameterTypes relates to a varargs method
	 * @param converter the converter to use for type conversions
	 * @param arguments the arguments to convert to the requested parameter types
229
	 * @throws SpelEvaluationException if there is a problem with conversion
230 231
	 */
	public static void convertAllArguments(Class[] parameterTypes, boolean isVarargs, TypeConverter converter,
232
			Object[] arguments) throws SpelEvaluationException {
233

234 235
		Assert.notNull(arguments,"should not be called if nothing to convert");
		
236 237
		Class varargsType = null;
		if (isVarargs) {
238
			Assert.isTrue(parameterTypes[parameterTypes.length-1].isArray(),"if varargs then last parameter type must be array");
239 240 241 242 243 244
			varargsType = parameterTypes[parameterTypes.length - 1].getComponentType();
		}
		for (int i = 0; i < arguments.length; i++) {
			Class<?> targetType = null;
			if (isVarargs && i >= (parameterTypes.length - 1)) {
				targetType = varargsType;
245
			} else {
246 247 248 249
				targetType = parameterTypes[i];
			}
			try {
				if (arguments[i] != null && arguments[i].getClass() != targetType) {
250
					if (converter == null) {
251
						throw new SpelEvaluationException(SpelMessage.TYPE_CONVERSION_ERROR, arguments[i].getClass().getName(),targetType);
252
					}
253 254
					arguments[i] = converter.convertValue(arguments[i], targetType);
				}
255
			} catch (EvaluationException ex) {
256
				// allows for another type converter throwing a different kind of EvaluationException
257 258
				if (ex instanceof SpelEvaluationException) {
					throw (SpelEvaluationException)ex;
259
				} else {
260
					throw new SpelEvaluationException(ex, SpelMessage.TYPE_CONVERSION_ERROR,arguments[i].getClass().getName(),targetType);
261 262 263 264 265 266 267 268 269 270
				}
			}
		}
	}

	/**
	 * Package up the arguments so that they correctly match what is expected in parameterTypes. For example, if
	 * parameterTypes is (int, String[]) because the second parameter was declared String... then if arguments is
	 * [1,"a","b"] then it must be repackaged as [1,new String[]{"a","b"}] in order to match the expected
	 * parameterTypes.
271
	 * @param requiredParameterTypes the types of the parameters for the invocation
272 273 274
	 * @param args the arguments to be setup ready for the invocation
	 * @return a repackaged array of arguments where any varargs setup has been done
	 */
275
	public static Object[] setupArgumentsForVarargsInvocation(Class[] requiredParameterTypes, Object... args) {
276
		// Check if array already built for final argument
277 278
		int parameterCount = requiredParameterTypes.length;
		int argumentCount = args.length;
279 280

		// Check if repackaging is needed:
281
		if (parameterCount != args.length || requiredParameterTypes[parameterCount - 1] != (args[argumentCount - 1] == null ? null : args[argumentCount - 1].getClass())) {
282
			int arraySize = 0; // zero size array if nothing to pass as the varargs parameter
283 284
			if (argumentCount >= parameterCount) {
				arraySize = argumentCount - (parameterCount - 1);
285
			}
286
			Object[] repackagedArguments = (Object[]) Array.newInstance(requiredParameterTypes[parameterCount - 1].getComponentType(),
287 288 289 290
					arraySize);

			// Copy all but the varargs arguments
			for (int i = 0; i < arraySize; i++) {
291
				repackagedArguments[i] = args[parameterCount + i - 1];
292 293
			}
			// Create an array for the varargs arguments
294
			Object[] newArgs = new Object[parameterCount];
295 296 297 298 299 300 301 302 303 304
			for (int i = 0; i < newArgs.length - 1; i++) {
				newArgs[i] = args[i];
			}
			newArgs[newArgs.length - 1] = repackagedArguments;
			return newArgs;
		}
		return args;
	}


305
	public static enum ArgsMatchKind {
306 307 308 309 310 311
		// An exact match is where the parameter types exactly match what the method/constructor being invoked is expecting
		EXACT, 
		// A close match is where the parameter types either exactly match or are assignment compatible with the method/constructor being invoked
		CLOSE, 
		// A conversion match is where the type converter must be used to transform some of the parameter types
		REQUIRES_CONVERSION
312 313 314 315 316 317 318 319 320
	}


	/**
	 * An instance of ArgumentsMatchInfo describes what kind of match was achieved between two sets of arguments - the set that a
	 * method/constructor is expecting and the set that are being supplied at the point of invocation. If the kind
	 * indicates that conversion is required for some of the arguments then the arguments that require conversion are
	 * listed in the argsRequiringConversion array.
	 */
321
	public static class ArgumentsMatchInfo {
322 323 324 325 326 327 328 329 330 331 332 333 334

		public ArgsMatchKind kind;

		public int[] argsRequiringConversion;

		ArgumentsMatchInfo(ArgsMatchKind kind, int[] integers) {
			this.kind = kind;
			argsRequiringConversion = integers;
		}

		ArgumentsMatchInfo(ArgsMatchKind kind) {
			this.kind = kind;
		}
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
		
		public boolean isExactMatch() {
			return kind==ArgsMatchKind.EXACT;
		}
		
		public boolean isCloseMatch() {
			return kind==ArgsMatchKind.CLOSE;
		}

		public boolean isMatchRequiringConversion() {
			return kind==ArgsMatchKind.REQUIRES_CONVERSION;
		}
		
		public String toString() {
			StringBuffer sb = new StringBuffer();
			sb.append("ArgumentMatch: ").append(kind);
			if (argsRequiringConversion!=null) {
				sb.append("  (argsForConversion:");
				for (int i=0;i<argsRequiringConversion.length;i++) {
					if (i>0) {
						sb.append(",");
					}
					sb.append(argsRequiringConversion[i]);
				}
				sb.append(")");
			}
			return sb.toString();
		}
363 364 365
	}

}