class ValidationHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

		ModelMap model = mavContainer.getModel();

		if (!model.isEmpty()) {

            int lastIndex = model.size() - 1;
            String lastKey = new ArrayList<>(model.keySet()).get(lastIndex);

            if (lastKey.startsWith(BindingResult.MODEL_KEY_PREFIX)) {

                // create a new ValidationHandler that wraps a BindingResult
                BindingResult bindingResult = (BindingResult) model.get(lastKey);
                ValidationHandler validationHandler = newBindingResultHandler(bindingResult);

                // if the BindingResult was targeting a @ModelAttribute that is also a BindingResultTarget,
                // get this ValidationHandler to automatically set any errors it'll encounter on the
                // BindingResultTarget upon error
                int secondToLastIndex = model.size() - 2;
                String secondToLastKey = new ArrayList<>(model.keySet()).get(secondToLastIndex);
                Object bindingResultTarget = model.get(secondToLastKey);

                if (bindingResultTarget instanceof BindingResultTarget) {
                    validationHandler.setBindingResultTarget((BindingResultTarget) bindingResultTarget);
                }

                return validationHandler;
			}
		}

		throw new IllegalStateException(
				"A ValidationHandler argument is expected to be declared immediately after a BindingResult " +
						"for a model attribute to which they apply, or the model attribute itself: " + parameter.getMethod());
	}

}