Support instantiating Kotlin classes with optional parameters
This commit updates BeanUtils class in order to add Kotlin optional parameters with default values support to the immutable data classes support introduced by SPR-15199. Issue: SPR-15673
This commit is contained in:
@@ -59,6 +59,7 @@ import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
* @author Juergen Hoeller
|
||||
* @author Sebastien Deleuze
|
||||
* @since 3.1
|
||||
*/
|
||||
public class ModelAttributeMethodProcessor implements HandlerMethodArgumentResolver, HandlerMethodReturnValueHandler {
|
||||
@@ -157,13 +158,13 @@ public class ModelAttributeMethodProcessor implements HandlerMethodArgumentResol
|
||||
protected Object createAttribute(String attributeName, MethodParameter parameter,
|
||||
WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception {
|
||||
|
||||
Constructor<?>[] ctors = parameter.getParameterType().getConstructors();
|
||||
if (ctors.length != 1) {
|
||||
// No standard data class or standard JavaBeans arrangement ->
|
||||
// defensively go with default constructor, expecting regular bean property bindings.
|
||||
return BeanUtils.instantiateClass(parameter.getParameterType());
|
||||
Class<?> type = parameter.getParameterType();
|
||||
|
||||
Constructor<?> ctor = BeanUtils.findPrimaryConstructor(type);
|
||||
if (ctor == null) {
|
||||
throw new IllegalStateException("No primary constructor found for " + type.getName());
|
||||
}
|
||||
Constructor<?> ctor = ctors[0];
|
||||
|
||||
if (ctor.getParameterCount() == 0) {
|
||||
// A single default constructor -> clearly a standard JavaBeans arrangement.
|
||||
return BeanUtils.instantiateClass(ctor);
|
||||
@@ -179,8 +180,9 @@ public class ModelAttributeMethodProcessor implements HandlerMethodArgumentResol
|
||||
Object[] args = new Object[paramTypes.length];
|
||||
WebDataBinder binder = binderFactory.createBinder(webRequest, null, attributeName);
|
||||
for (int i = 0; i < paramNames.length; i++) {
|
||||
args[i] = binder.convertIfNecessary(
|
||||
webRequest.getParameterValues(paramNames[i]), paramTypes[i], new MethodParameter(ctor, i));
|
||||
String[] parameterValues = webRequest.getParameterValues(paramNames[i]);
|
||||
args[i] = (parameterValues != null ? binder.convertIfNecessary(parameterValues, paramTypes[i],
|
||||
new MethodParameter(ctor, i)) : null);
|
||||
}
|
||||
return BeanUtils.instantiateClass(ctor, args);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user