Closed
Description
Sam Brannen opened SPR-14055 and commented
Status Quo
A MethodParameter
or SynthesizingMethodParameter
can be created from a Method
and an index
; however, there is currently no first-class support for creating a MethodParameter
from a java.lang.reflect.Parameter
.
Related Resources
The MethodParameterFactory
in the spring-test
project has factory methods for creating a MethodParameter
or SynthesizingMethodParameter
from a Java 8 Parameter
.
The trick involves retrieving the java.lang.reflect.Executable
from the supplied Parameter
and then determining the index
of the corresponding parameter.
The following code excerpts demonstrate the technique.
public static MethodParameter createMethodParameter(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
if (executable instanceof Method) {
return new MethodParameter((Method) executable, getIndex(parameter));
}
// else
return new MethodParameter((Constructor<?>) executable, getIndex(parameter));
}
private static int getIndex(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
Parameter[] parameters = executable.getParameters();
for (int i = 0; i < parameters.length; i++) {
if (parameters[i] == parameter) {
return i;
}
}
throw new IllegalStateException(String.format("Failed to resolve index of parameter [%s] in executable [%s]",
parameter, executable.toGenericString()));
}
Deliverables
- Support creation of a
MethodParameter
from ajava.lang.reflect.Parameter
. - Support creation of a
SynthesizingMethodParameter
from ajava.lang.reflect.Parameter
.
Issue Links:
- Introduce support for JUnit 5 in the TestContext framework [SPR-13575] #18151 Introduce support for JUnit 5 in the TestContext framework ("is depended on by")
- Support creation of SynthesizingMethodParameter for constructor parameter [SPR-14054] #18626 Support creation of SynthesizingMethodParameter for constructor parameter
- MethodParameter should not be equal to SynthesizingMethodParameter [SPR-14438] #19009 MethodParameter should not be equal to SynthesizingMethodParameter
- Validate method parameter index via Java 8 Method.getParameterCount() [SPR-13456] #18036 Validate method parameter index via Java 8 Method.getParameterCount()