Support java.util.Optional for @MVC named value args

After this change, java.util.Optional is supported with @RequestParam,
@RequestHeader, and @MatrixVariable arguments in Java 8. When Optional
is used the required flag is effectively ignored.

Issue: SPR-11829
This commit is contained in:
Rossen Stoyanchev
2014-06-12 23:50:26 -04:00
parent c2356e57c8
commit 0dc6082b01
9 changed files with 185 additions and 10 deletions

View File

@@ -53,6 +53,19 @@ class TypeConverterDelegate {
private static final Log logger = LogFactory.getLog(TypeConverterDelegate.class);
/** Java 8's java.util.Optional.empty() instance */
private static Object javaUtilOptionalEmpty = null;
static {
try {
Class<?> clazz = ClassUtils.forName("java.util.Optional", TypeConverterDelegate.class.getClassLoader());
javaUtilOptionalEmpty = ClassUtils.getMethod(clazz, "empty").invoke(null);
} catch (Exception ex) {
// Java 8 not available - conversion to Optional not supported then.
}
}
private final PropertyEditorRegistrySupport propertyEditorRegistry;
private final Object targetObject;
@@ -244,6 +257,9 @@ class TypeConverterDelegate {
standardConversion = true;
}
}
else if (requiredType.equals(javaUtilOptionalEmpty.getClass())) {
convertedValue = javaUtilOptionalEmpty;
}
if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
if (firstAttemptEx != null) {