Skip to content

Commit

Permalink
Polish Spel's ReflectionHelper.setupArgumentsForVarargsInvocation()
Browse files Browse the repository at this point in the history
  • Loading branch information
sbrannen committed Oct 22, 2021
1 parent 9af11ad commit 9b96777
Showing 1 changed file with 13 additions and 12 deletions.
Expand Up @@ -332,8 +332,8 @@ private static boolean isFirstEntryInArray(Object value, @Nullable Object possib
}

/**
* Package up the arguments so that they correctly match what is expected in parameterTypes.
* For example, if parameterTypes is {@code (int, String[])} because the second parameter
* 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
Expand All @@ -350,23 +350,24 @@ public static Object[] setupArgumentsForVarargsInvocation(Class<?>[] requiredPar
requiredParameterTypes[parameterCount - 1] !=
(args[argumentCount - 1] != null ? args[argumentCount - 1].getClass() : null)) {

int arraySize = 0; // zero size array if nothing to pass as the varargs parameter
if (argumentCount >= parameterCount) {
arraySize = argumentCount - (parameterCount - 1);
}

// Create an array for the varargs arguments
// 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 = requiredParameterTypes[parameterCount - 1].getComponentType();
Object repackagedArgs = Array.newInstance(componentType, arraySize);
for (int i = 0; i < arraySize; i++) {
Array.set(repackagedArgs, i, args[parameterCount - 1 + i]);
Object varargsArray = Array.newInstance(componentType, varargsArraySize);
for (int i = 0; i < varargsArraySize; i++) {
Array.set(varargsArray, i, args[parameterCount - 1 + i]);
}
newArgs[newArgs.length - 1] = repackagedArgs;
// Finally, add the varargs array to the new arguments array.
newArgs[newArgs.length - 1] = varargsArray;
return newArgs;
}
return args;
Expand Down

0 comments on commit 9b96777

Please sign in to comment.