當前位置: 首頁>>代碼示例>>Java>>正文


Java TypeMismatchException類代碼示例

本文整理匯總了Java中org.springframework.beans.TypeMismatchException的典型用法代碼示例。如果您正苦於以下問題:Java TypeMismatchException類的具體用法?Java TypeMismatchException怎麽用?Java TypeMismatchException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


TypeMismatchException類屬於org.springframework.beans包,在下文中一共展示了TypeMismatchException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testCustomConversionService

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
	loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 14);

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	mapping.setDefaultHandler(handlerMethod);

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
	request.setRequestURI("/accounts/12345");
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();

	HandlerExecutionChain chain = mapping.getHandler(request);
	assertEquals(1, chain.getInterceptors().length);
	assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
	ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
	interceptor.preHandle(request, response, handler);
	assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	adapter.handle(request, response, handlerMethod);
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:26,代碼來源:MvcNamespaceTests.java

示例2: canConvert

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
public boolean canConvert(Object source, ReifiedType targetType) {
	Class<?> required = targetType.getRawClass();
	try {
		getConverter().convertIfNecessary(source, required);
		return true;
	} catch (TypeMismatchException ex) {
		return false;
	}
}
 
開發者ID:eclipse,項目名稱:gemini.blueprint,代碼行數:10,代碼來源:SpringBlueprintConverter.java

示例3: afterPropertiesSet

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
/**
 * Look up the JNDI object and store it.
 */
@Override
public void afterPropertiesSet() throws IllegalArgumentException, NamingException {
	super.afterPropertiesSet();

	if (this.proxyInterfaces != null || !this.lookupOnStartup || !this.cache || this.exposeAccessContext) {
		// We need to create a proxy for this...
		if (this.defaultObject != null) {
			throw new IllegalArgumentException(
					"'defaultObject' is not supported in combination with 'proxyInterface'");
		}
		// We need a proxy and a JndiObjectTargetSource.
		this.jndiObject = JndiObjectProxyFactory.createJndiObjectProxy(this);
	}
	else {
		if (this.defaultObject != null && getExpectedType() != null &&
				!getExpectedType().isInstance(this.defaultObject)) {
			TypeConverter converter = (this.beanFactory != null ?
					this.beanFactory.getTypeConverter() : new SimpleTypeConverter());
			try {
				this.defaultObject = converter.convertIfNecessary(this.defaultObject, getExpectedType());
			}
			catch (TypeMismatchException ex) {
				throw new IllegalArgumentException("Default object [" + this.defaultObject + "] of type [" +
						this.defaultObject.getClass().getName() + "] is not of expected type [" +
						getExpectedType().getName() + "] and cannot be converted either", ex);
			}
		}
		// Locate specified JNDI object.
		this.jndiObject = lookupWithFallback();
	}
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:35,代碼來源:JndiObjectFactoryBean.java

示例4: readFromSource

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
@Override
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
	Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required");
	try {
		Object result = this.unmarshaller.unmarshal(source);
		if (!clazz.isInstance(result)) {
			throw new TypeMismatchException(result, clazz);
		}
		return result;
	}
	catch (UnmarshallingFailureException ex) {
		throw new HttpMessageNotReadableException("Could not read [" + clazz + "]", ex);
	}
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:15,代碼來源:MarshallingHttpMessageConverter.java

示例5: handleTypeMismatch

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
@Override
protected ResponseEntity<Object> handleTypeMismatch(final TypeMismatchException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = ex.getValue() + " value for " + ex.getPropertyName() + " should be of type " + ex.getRequiredType();

    final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
開發者ID:junneyang,項目名稱:xxproject,代碼行數:10,代碼來源:CustomRestExceptionHandler.java

示例6: handleTypeMismatch

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
@Override
protected ResponseEntity<Object> handleTypeMismatch(final TypeMismatchException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
	logger.info(ex.getClass().getName());
	//
	final String error = ex.getValue() + " value for " + ex.getPropertyName() + " should be of type " + ex.getRequiredType();

	final AitException AitException = new AitException(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
	return handleExceptionInternal(ex, AitException, headers, AitException.getStatus(), request);
}
 
開發者ID:allianzit,項目名稱:ait-platform,代碼行數:10,代碼來源:AitRestExceptionHandler.java

示例7: testContextWithInvalidValueType

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
@Test
public void testContextWithInvalidValueType() throws IOException {
	ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
			new String[] {INVALID_VALUE_TYPE_CONTEXT}, false);
	try {
		context.refresh();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(TypeMismatchException.class));
		assertTrue(ex.toString().contains("someMessageSource"));
		assertTrue(ex.toString().contains("useCodeAsDefaultMessage"));
		checkExceptionFromInvalidValueType(ex);
		checkExceptionFromInvalidValueType(new ExceptionInInitializerError(ex));
		assertFalse(context.isActive());
	}
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:18,代碼來源:ClassPathXmlApplicationContextTests.java

示例8: nestedException

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
@Test
public void nestedException() throws Exception {
	Exception cause = new StatusCodeAndReasonMessageException();
	TypeMismatchException ex = new TypeMismatchException("value", ITestBean.class, cause);
	ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
	assertNotNull("No ModelAndView returned", mav);
	assertTrue("No Empty ModelAndView returned", mav.isEmpty());
	assertEquals("Invalid status code", 410, response.getStatus());
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:10,代碼來源:ResponseStatusExceptionResolverTests.java

示例9: resolvePreparedArguments

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(
		String beanName, RootBeanDefinition mbd, BeanWrapper bw, Member methodOrCtor, Object[] argsToResolve) {

	Class<?>[] paramTypes = (methodOrCtor instanceof Method ?
			((Method) methodOrCtor).getParameterTypes() : ((Constructor<?>) methodOrCtor).getParameterTypes());
	TypeConverter converter = (this.beanFactory.getCustomTypeConverter() != null ?
			this.beanFactory.getCustomTypeConverter() : bw);
	BeanDefinitionValueResolver valueResolver =
			new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
	Object[] resolvedArgs = new Object[argsToResolve.length];
	for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
		Object argValue = argsToResolve[argIndex];
		MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, argIndex);
		GenericTypeResolver.resolveParameterType(methodParam, methodOrCtor.getDeclaringClass());
		if (argValue instanceof AutowiredArgumentMarker) {
			argValue = resolveAutowiredArgument(methodParam, beanName, null, converter);
		}
		else if (argValue instanceof BeanMetadataElement) {
			argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
		}
		else if (argValue instanceof String) {
			argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
		}
		Class<?> paramType = paramTypes[argIndex];
		try {
			resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
		}
		catch (TypeMismatchException ex) {
			String methodType = (methodOrCtor instanceof Constructor ? "constructor" : "factory method");
			throw new UnsatisfiedDependencyException(
					mbd.getResourceDescription(), beanName, argIndex, paramType,
					"Could not convert " + methodType + " argument value of type [" +
					ObjectUtils.nullSafeClassName(argValue) +
					"] to required type [" + paramType.getName() + "]: " + ex.getMessage());
		}
	}
	return resolvedArgs;
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:42,代碼來源:ConstructorResolver.java

示例10: convertIfNecessary

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
@Override
@SuppressWarnings("unchecked")
public Object convertIfNecessary(Object value, Class requiredType) {
	if (value instanceof String && Float.class.isAssignableFrom(requiredType)) {
		try {
			return new Float(this.numberFormat.parse((String) value).floatValue());
		}
		catch (ParseException ex) {
			throw new TypeMismatchException(value, requiredType, ex);
		}
	}
	else if (value instanceof String && int.class.isAssignableFrom(requiredType)) {
		return new Integer(5);
	}
	else {
		return value;
	}
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:19,代碼來源:DefaultListableBeanFactoryTests.java

示例11: getTaskUtil

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
protected TaskUtil getTaskUtil(final Task task) {
    TaskUtil result = (task instanceof PropagationTask)
            ? TaskUtil.PROPAGATION
            : (task instanceof NotificationTask)
            ? TaskUtil.NOTIFICATION
            : (task instanceof SyncTask)
            ? TaskUtil.SYNC
            : (task instanceof SchedTask)
            ? TaskUtil.SCHED
            : null;

    if (result == null) {
        LOG.error("Task not supported: " + task.getClass().getName());

        throw new TypeMismatchException(task.getClass().getName(),
                TaskUtil.class);
    }

    return result;
}
 
開發者ID:ilgrosso,項目名稱:oldSyncopeIdM,代碼行數:21,代碼來源:AbstractController.java

示例12: testCustomConversionService

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
@Test(expected=TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
	loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 12);

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	mapping.setDefaultHandler(handlerMethod);

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
	request.setRequestURI("/accounts/12345");
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();

	HandlerExecutionChain chain = mapping.getHandler(request);
	assertEquals(1, chain.getInterceptors().length);
	assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
	ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
	interceptor.preHandle(request, response, handler);
	assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	adapter.handle(request, response, handlerMethod);
}
 
開發者ID:deathspeeder,項目名稱:class-guard,代碼行數:26,代碼來源:MvcNamespaceTests.java

示例13: getParamErrors

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
/**
 * TypeMismatchException中獲取到參數錯誤類型
 *
 * @param e
 */
private ModelAndView getParamErrors(TypeMismatchException e) {

    Throwable t = e.getCause();

    if (t instanceof ConversionFailedException) {

        ConversionFailedException x = (ConversionFailedException) t;
        TypeDescriptor type = x.getTargetType();
        Annotation[] annotations = type != null ? type.getAnnotations() : new Annotation[0];
        Map<String, String> errors = new HashMap<String, String>();
        for (Annotation a : annotations) {
            if (a instanceof RequestParam) {
                errors.put(((RequestParam) a).value(), "parameter type error!");
            }
        }
        if (errors.size() > 0) {
            return paramError(errors, ErrorCode.TYPE_MIS_MATCH);
        }
    }

    JsonObjectBase jsonObject = JsonObjectUtils.buildGlobalError("parameter type error!", ErrorCode.TYPE_MIS_MATCH);
    return JsonObjectUtils.JsonObjectError2ModelView((JsonObjectError) jsonObject);
}
 
開發者ID:knightliao,項目名稱:disconf,代碼行數:29,代碼來源:MyExceptionHandler.java

示例14: handleTypeMismatch

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
@Test
public void handleTypeMismatch() {
	TypeMismatchException ex = new TypeMismatchException("foo", String.class);
	ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
	assertNotNull("No ModelAndView returned", mav);
	assertTrue("No Empty ModelAndView returned", mav.isEmpty());
	assertEquals("Invalid status code", 400, response.getStatus());
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:9,代碼來源:DefaultHandlerExceptionResolverTests.java

示例15: testMappingNullValue

import org.springframework.beans.TypeMismatchException; //導入依賴的package包/類
@Test
public void testMappingNullValue() throws Exception {
	BeanPropertyRowMapper<Person> mapper = new BeanPropertyRowMapper<Person>(Person.class);
	Mock mock = new Mock(MockType.TWO);
	thrown.expect(TypeMismatchException.class);
	mock.getJdbcTemplate().query(
			"select name, null as age, birth_date, balance from people", mapper);
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:9,代碼來源:BeanPropertyRowMapperTests.java


注:本文中的org.springframework.beans.TypeMismatchException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。