forked from spring-projects/spring-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReflectionHelper.java
547 lines (498 loc) · 23.2 KB
/
ReflectionHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/*
* Copyright 2002-2024 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
*
* https://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.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import java.lang.reflect.Array;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.TypeConverter;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MethodInvoker;
import static org.springframework.util.ObjectUtils.isArray;
/**
* Utility methods used by the reflection resolver code to discover the appropriate
* methods, constructors, and fields that should be used in expressions.
*
* @author Andy Clement
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.0
*/
public abstract class ReflectionHelper {
/**
* Compare argument arrays and return information about whether they match.
* <p>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 types the method/constructor is expecting
* @param suppliedArgTypes the 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 {@code null} if it was not a match
*/
@Nullable
static ArgumentsMatchInfo compareArguments(
List<TypeDescriptor> expectedArgTypes, List<TypeDescriptor> suppliedArgTypes, TypeConverter typeConverter) {
Assert.isTrue(expectedArgTypes.size() == suppliedArgTypes.size(),
"Expected argument types and supplied argument types should be arrays of same length");
ArgumentsMatchKind match = ArgumentsMatchKind.EXACT;
for (int i = 0; i < expectedArgTypes.size() && match != null; i++) {
TypeDescriptor suppliedArg = suppliedArgTypes.get(i);
TypeDescriptor expectedArg = expectedArgTypes.get(i);
// The user may supply null, and that will be OK unless a primitive is expected.
if (suppliedArg == null) {
if (expectedArg.isPrimitive()) {
match = null;
}
}
else if (!expectedArg.equals(suppliedArg)) {
if (suppliedArg.isAssignableTo(expectedArg)) {
if (match != ArgumentsMatchKind.REQUIRES_CONVERSION) {
match = ArgumentsMatchKind.CLOSE;
}
}
else if (typeConverter.canConvert(suppliedArg, expectedArg)) {
match = ArgumentsMatchKind.REQUIRES_CONVERSION;
}
else {
match = null;
}
}
}
return (match != null ? new ArgumentsMatchInfo(match) : null);
}
/**
* Based on {@link MethodInvoker#getTypeDifferenceWeight(Class[], Object[])} but operates on TypeDescriptors.
*/
public static int getTypeDifferenceWeight(List<TypeDescriptor> paramTypes, List<TypeDescriptor> argTypes) {
int result = 0;
for (int i = 0; i < paramTypes.size(); i++) {
TypeDescriptor paramType = paramTypes.get(i);
TypeDescriptor argType = (i < argTypes.size() ? argTypes.get(i) : null);
if (argType == null) {
if (paramType.isPrimitive()) {
return Integer.MAX_VALUE;
}
}
else {
Class<?> paramTypeClazz = paramType.getType();
if (!ClassUtils.isAssignable(paramTypeClazz, argType.getType())) {
return Integer.MAX_VALUE;
}
if (paramTypeClazz.isPrimitive()) {
paramTypeClazz = Object.class;
}
Class<?> superClass = argType.getType().getSuperclass();
while (superClass != null) {
if (paramTypeClazz.equals(superClass)) {
result = result + 2;
superClass = null;
}
else if (ClassUtils.isAssignable(paramTypeClazz, superClass)) {
result = result + 2;
superClass = superClass.getSuperclass();
}
else {
superClass = null;
}
}
if (paramTypeClazz.isInterface()) {
result = result + 1;
}
}
}
return result;
}
/**
* Compare argument arrays and return information about whether they match.
* <p>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. This variant of {@link #compareArguments} also allows for a varargs match.
* @param expectedArgTypes the types the method/constructor is expecting
* @param suppliedArgTypes the 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 {@code null} if it was not a match
*/
@Nullable
static ArgumentsMatchInfo compareArgumentsVarargs(
List<TypeDescriptor> expectedArgTypes, List<TypeDescriptor> suppliedArgTypes, TypeConverter typeConverter) {
Assert.isTrue(!CollectionUtils.isEmpty(expectedArgTypes),
"Expected arguments must at least include one array (the varargs parameter)");
Assert.isTrue(expectedArgTypes.get(expectedArgTypes.size() - 1).isArray(),
"Final expected argument should be array type (the varargs parameter)");
ArgumentsMatchKind match = ArgumentsMatchKind.EXACT;
// Check up until the varargs argument:
// Deal with the arguments up to 'expected number' - 1 (that is everything but the varargs argument)
int argCountUpToVarargs = expectedArgTypes.size() - 1;
for (int i = 0; i < argCountUpToVarargs && match != null; i++) {
TypeDescriptor suppliedArg = suppliedArgTypes.get(i);
TypeDescriptor expectedArg = expectedArgTypes.get(i);
if (suppliedArg == null) {
if (expectedArg.isPrimitive()) {
match = null;
}
}
else {
if (!expectedArg.equals(suppliedArg)) {
if (suppliedArg.isAssignableTo(expectedArg)) {
if (match != ArgumentsMatchKind.REQUIRES_CONVERSION) {
match = ArgumentsMatchKind.CLOSE;
}
}
else if (typeConverter.canConvert(suppliedArg, expectedArg)) {
match = ArgumentsMatchKind.REQUIRES_CONVERSION;
}
else {
match = null;
}
}
}
}
// If already confirmed it cannot be a match, then return
if (match == null) {
return null;
}
if (suppliedArgTypes.size() == expectedArgTypes.size() &&
expectedArgTypes.get(expectedArgTypes.size() - 1).equals(
suppliedArgTypes.get(suppliedArgTypes.size() - 1))) {
// 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. Proceed with it.
}
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.
TypeDescriptor varargsDesc = expectedArgTypes.get(expectedArgTypes.size() - 1);
TypeDescriptor elementDesc = varargsDesc.getElementTypeDescriptor();
Assert.state(elementDesc != null, "No element type");
Class<?> varargsParamType = elementDesc.getType();
// All remaining parameters must be of this type or convertible to this type
for (int i = expectedArgTypes.size() - 1; i < suppliedArgTypes.size(); i++) {
TypeDescriptor suppliedArg = suppliedArgTypes.get(i);
if (suppliedArg == null) {
if (varargsParamType.isPrimitive()) {
match = null;
}
}
else {
if (varargsParamType != suppliedArg.getType()) {
if (ClassUtils.isAssignable(varargsParamType, suppliedArg.getType())) {
if (match != ArgumentsMatchKind.REQUIRES_CONVERSION) {
match = ArgumentsMatchKind.CLOSE;
}
}
else if (typeConverter.canConvert(suppliedArg, TypeDescriptor.valueOf(varargsParamType))) {
match = ArgumentsMatchKind.REQUIRES_CONVERSION;
}
else {
match = null;
}
}
}
}
}
return (match != null ? new ArgumentsMatchInfo(match) : null);
}
/**
* Convert the supplied set of arguments into the parameter types specified
* by the supplied {@link Method}.
* <p>The arguments are converted 'in-place' in the input array.
* <p>If the method accepts varargs, the final entry in its parameterTypes
* array is going to be an array itself whose component type will be used as
* the conversion target for any additional 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.
* <p>This method does <strong>not</strong> repackage the arguments into a
* form suitable for the varargs invocation. A subsequent call to
* {@link #setupArgumentsForVarargsInvocation(Class[], Object...)} must be
* used for that.
* @param converter the converter to use for type conversions
* @param arguments the arguments to convert to the parameter types of the
* target method
* @param method the target method
* @return true if some kind of conversion occurred on an argument
* @throws SpelEvaluationException if there is a problem with conversion
*/
public static boolean convertAllArguments(TypeConverter converter, Object[] arguments, Method method)
throws SpelEvaluationException {
Integer varargsPosition = (method.isVarArgs() ? method.getParameterCount() - 1 : null);
return convertArguments(converter, arguments, method, varargsPosition);
}
/**
* Takes an input set of argument values and converts them to the parameter
* types of the supplied {@link Executable} (i.e., constructor or method).
* <p>The arguments are converted 'in-place' in the input array.
* @param converter the type converter to use for attempting conversions
* @param arguments the actual arguments that need conversion
* @param executable the target Method or Constructor
* @param varargsPosition the known position of the varargs argument, if any
* ({@code null} if not varargs)
* @return {@code true} if some kind of conversion occurred on an argument
* @throws EvaluationException if a problem occurs during conversion
*/
static boolean convertArguments(TypeConverter converter, Object[] arguments, Executable executable,
@Nullable Integer varargsPosition) throws EvaluationException {
boolean conversionOccurred = false;
if (varargsPosition == null) {
for (int i = 0; i < arguments.length; i++) {
TypeDescriptor targetType = new TypeDescriptor(MethodParameter.forExecutable(executable, i));
Object argument = arguments[i];
arguments[i] = converter.convertValue(argument, TypeDescriptor.forObject(argument), targetType);
conversionOccurred |= (argument != arguments[i]);
}
}
else {
// Convert everything up to the varargs position
for (int i = 0; i < varargsPosition; i++) {
TypeDescriptor targetType = new TypeDescriptor(MethodParameter.forExecutable(executable, i));
Object argument = arguments[i];
arguments[i] = converter.convertValue(argument, TypeDescriptor.forObject(argument), targetType);
conversionOccurred |= (argument != arguments[i]);
}
MethodParameter methodParam = MethodParameter.forExecutable(executable, varargsPosition);
// If the target is varargs and there is just one more argument, then convert it here.
if (varargsPosition == arguments.length - 1) {
Object argument = arguments[varargsPosition];
TypeDescriptor targetType = new TypeDescriptor(methodParam);
TypeDescriptor sourceType = TypeDescriptor.forObject(argument);
if (argument == null) {
// Perform the equivalent of GenericConversionService.convertNullSource() for a single argument.
TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();
if (elementDesc != null && elementDesc.getObjectType() == Optional.class) {
arguments[varargsPosition] = Optional.empty();
conversionOccurred = true;
}
}
// If the argument type is equal to the varargs element type, there is no need to
// convert it or wrap it in an array. For example, using StringToArrayConverter to
// convert a String containing a comma would result in the String being split and
// repackaged in an array when it should be used as-is.
else if (!sourceType.equals(targetType.getElementTypeDescriptor())) {
arguments[varargsPosition] = converter.convertValue(argument, sourceType, targetType);
}
// Possible outcomes of the above if-else block:
// 1) the input argument was null, and nothing was done.
// 2) the input argument was null; the varargs element type is Optional; and the argument was converted to Optional.empty().
// 3) the input argument was correct type but not wrapped in an array, and nothing was done.
// 4) the input argument was already compatible (i.e., array of valid type), and nothing was done.
// 5) the input argument was the wrong type and got converted and wrapped in an array.
if (argument != arguments[varargsPosition] &&
!isFirstEntryInArray(argument, arguments[varargsPosition])) {
conversionOccurred = true; // case 5
}
}
// Otherwise, convert remaining arguments to the varargs element type.
else {
TypeDescriptor targetType = new TypeDescriptor(methodParam).getElementTypeDescriptor();
Assert.state(targetType != null, "No element type");
for (int i = varargsPosition; i < arguments.length; i++) {
Object argument = arguments[i];
arguments[i] = converter.convertValue(argument, TypeDescriptor.forObject(argument), targetType);
conversionOccurred |= (argument != arguments[i]);
}
}
}
return conversionOccurred;
}
/**
* Takes an input set of argument values and converts them to the parameter
* types of the supplied {@link MethodHandle}.
* <p>The arguments are converted 'in-place' in the input array.
* @param converter the type converter to use for attempting conversions
* @param arguments the actual arguments that need conversion
* @param methodHandle the target MethodHandle
* @param varargsPosition the known position of the varargs argument, if any
* ({@code null} if not varargs)
* @return {@code true} if some kind of conversion occurred on an argument
* @throws EvaluationException if a problem occurs during conversion
* @since 6.1
*/
public static boolean convertAllMethodHandleArguments(TypeConverter converter, Object[] arguments,
MethodHandle methodHandle, @Nullable Integer varargsPosition) throws EvaluationException {
boolean conversionOccurred = false;
final MethodType methodHandleArgumentTypes = methodHandle.type();
if (varargsPosition == null) {
for (int i = 0; i < arguments.length; i++) {
Class<?> argumentClass = methodHandleArgumentTypes.parameterType(i);
ResolvableType resolvableType = ResolvableType.forClass(argumentClass);
TypeDescriptor targetType = new TypeDescriptor(resolvableType, argumentClass, null);
Object argument = arguments[i];
arguments[i] = converter.convertValue(argument, TypeDescriptor.forObject(argument), targetType);
conversionOccurred |= (argument != arguments[i]);
}
}
else {
// Convert everything up to the varargs position
for (int i = 0; i < varargsPosition; i++) {
Class<?> argumentClass = methodHandleArgumentTypes.parameterType(i);
ResolvableType resolvableType = ResolvableType.forClass(argumentClass);
TypeDescriptor targetType = new TypeDescriptor(resolvableType, argumentClass, null);
Object argument = arguments[i];
arguments[i] = converter.convertValue(argument, TypeDescriptor.forObject(argument), targetType);
conversionOccurred |= (argument != arguments[i]);
}
final Class<?> varArgClass = methodHandleArgumentTypes.lastParameterType().componentType();
ResolvableType varArgResolvableType = ResolvableType.forClass(varArgClass);
TypeDescriptor varArgContentType = new TypeDescriptor(varArgResolvableType, varArgClass, null);
// If the target is varargs and there is just one more argument, then convert it here.
if (varargsPosition == arguments.length - 1) {
Object argument = arguments[varargsPosition];
TypeDescriptor sourceType = TypeDescriptor.forObject(argument);
if (argument == null) {
// Perform the equivalent of GenericConversionService.convertNullSource() for a single argument.
TypeDescriptor elementDesc = varArgContentType.getElementTypeDescriptor();
if (elementDesc != null && elementDesc.getObjectType() == Optional.class) {
arguments[varargsPosition] = Optional.empty();
conversionOccurred = true;
}
}
// If the argument type is equal to the varargs element type, there is no need to
// convert it or wrap it in an array. For example, using StringToArrayConverter to
// convert a String containing a comma would result in the String being split and
// repackaged in an array when it should be used as-is.
else if (!sourceType.equals(varArgContentType.getElementTypeDescriptor())) {
arguments[varargsPosition] = converter.convertValue(argument, sourceType, varArgContentType);
}
// Possible outcomes of the above if-else block:
// 1) the input argument was null, and nothing was done.
// 2) the input argument was null; the varargs element type is Optional; and the argument was converted to Optional.empty().
// 3) the input argument was correct type but not wrapped in an array, and nothing was done.
// 4) the input argument was already compatible (i.e., array of valid type), and nothing was done.
// 5) the input argument was the wrong type and got converted and wrapped in an array.
if (argument != arguments[varargsPosition] &&
!isFirstEntryInArray(argument, arguments[varargsPosition])) {
conversionOccurred = true; // case 5
}
}
// Otherwise, convert remaining arguments to the varargs element type.
else {
for (int i = varargsPosition; i < arguments.length; i++) {
Object argument = arguments[i];
arguments[i] = converter.convertValue(argument, TypeDescriptor.forObject(argument), varArgContentType);
conversionOccurred |= (argument != arguments[i]);
}
}
}
return conversionOccurred;
}
/**
* Check if the supplied value is the first entry in the array represented by the possibleArray value.
* @param value the value to check for in the array
* @param possibleArray an array object that may have the supplied value as the first element
* @return true if the supplied value is the first entry in the array
*/
private static boolean isFirstEntryInArray(Object value, @Nullable Object possibleArray) {
if (possibleArray == null) {
return false;
}
Class<?> type = possibleArray.getClass();
if (!type.isArray() || Array.getLength(possibleArray) == 0 ||
!ClassUtils.isAssignableValue(type.componentType(), value)) {
return false;
}
Object arrayValue = Array.get(possibleArray, 0);
return (type.componentType().isPrimitive() ? arrayValue.equals(value) : arrayValue == value);
}
/**
* Package up the arguments so that they correctly match what is expected in requiredParameterTypes.
* <p>For example, if requiredParameterTypes is {@code (int, String[])} because the second parameter
* was declared {@code String...}, then if arguments is {@code [1,"a","b"]} then it must be
* repackaged as {@code [1,new String[]{"a","b"}]} in order to match the expected types.
* @param requiredParameterTypes the types of the parameters for the invocation
* @param args the arguments to be setup ready for the invocation
* @return a repackaged array of arguments where any varargs setup has been done
*/
public static Object[] setupArgumentsForVarargsInvocation(Class<?>[] requiredParameterTypes, Object... args) {
int parameterCount = requiredParameterTypes.length;
Assert.notEmpty(requiredParameterTypes, "Required parameter types must not be empty");
Class<?> lastRequiredParameterType = requiredParameterTypes[parameterCount - 1];
Assert.isTrue(lastRequiredParameterType.isArray(), "Method must be varargs");
int argumentCount = args.length;
Object lastArgument = argumentCount > 0 ? args[argumentCount - 1] : null;
// Check if repackaging is needed...
if (parameterCount != args.length ||
(!isArray(lastArgument) && differentTypes(lastRequiredParameterType, lastArgument))) {
// Create an array for the leading arguments plus the varargs array argument.
Object[] newArgs = new Object[parameterCount];
// Copy all leading arguments to the new array, omitting the varargs array argument.
System.arraycopy(args, 0, newArgs, 0, newArgs.length - 1);
// Now sort out the final argument, which is the varargs one. Before entering this method,
// the arguments should have been converted to the box form of the required type.
int varargsArraySize = 0; // zero size array if nothing to pass as the varargs parameter
if (argumentCount >= parameterCount) {
varargsArraySize = argumentCount - (parameterCount - 1);
}
Class<?> componentType = lastRequiredParameterType.componentType();
Object varargsArray = Array.newInstance(componentType, varargsArraySize);
for (int i = 0; i < varargsArraySize; i++) {
Array.set(varargsArray, i, args[parameterCount - 1 + i]);
}
// Finally, add the varargs array to the new arguments array.
newArgs[newArgs.length - 1] = varargsArray;
return newArgs;
}
return args;
}
private static boolean differentTypes(Class<?> lastRequiredParameterType, @Nullable Object lastArgument) {
return lastArgument == null || lastRequiredParameterType != lastArgument.getClass();
}
/**
* Arguments match kinds.
*/
enum ArgumentsMatchKind {
/** An exact match is where the parameter types exactly match what the method/constructor is expecting. */
EXACT,
/** A close match is where the parameter types either exactly match or are assignment-compatible. */
CLOSE,
/** A conversion match is where the type converter must be used to transform some of the parameter types. */
REQUIRES_CONVERSION
}
/**
* 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.
*
* @param kind the kind of match that was achieved
*/
record ArgumentsMatchInfo(ArgumentsMatchKind kind) {
public boolean isExactMatch() {
return (this.kind == ArgumentsMatchKind.EXACT);
}
public boolean isCloseMatch() {
return (this.kind == ArgumentsMatchKind.CLOSE);
}
public boolean isMatchRequiringConversion() {
return (this.kind == ArgumentsMatchKind.REQUIRES_CONVERSION);
}
@Override
public String toString() {
return "ArgumentMatchInfo: " + this.kind;
}
}
}