001/* 002 * Copyright 2002-2016 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.beans; 018 019import java.lang.reflect.Field; 020 021import org.springframework.core.MethodParameter; 022import org.springframework.core.convert.ConversionException; 023import org.springframework.core.convert.ConverterNotFoundException; 024 025/** 026 * Base implementation of the {@link TypeConverter} interface, using a package-private delegate. 027 * Mainly serves as base class for {@link BeanWrapperImpl}. 028 * 029 * @author Juergen Hoeller 030 * @since 3.2 031 * @see SimpleTypeConverter 032 */ 033public abstract class TypeConverterSupport extends PropertyEditorRegistrySupport implements TypeConverter { 034 035 TypeConverterDelegate typeConverterDelegate; 036 037 038 @Override 039 public <T> T convertIfNecessary(Object value, Class<T> requiredType) throws TypeMismatchException { 040 return doConvert(value, requiredType, null, null); 041 } 042 043 @Override 044 public <T> T convertIfNecessary(Object value, Class<T> requiredType, MethodParameter methodParam) 045 throws TypeMismatchException { 046 047 return doConvert(value, requiredType, methodParam, null); 048 } 049 050 @Override 051 public <T> T convertIfNecessary(Object value, Class<T> requiredType, Field field) 052 throws TypeMismatchException { 053 054 return doConvert(value, requiredType, null, field); 055 } 056 057 private <T> T doConvert(Object value, Class<T> requiredType, MethodParameter methodParam, Field field) 058 throws TypeMismatchException { 059 try { 060 if (field != null) { 061 return this.typeConverterDelegate.convertIfNecessary(value, requiredType, field); 062 } 063 else { 064 return this.typeConverterDelegate.convertIfNecessary(value, requiredType, methodParam); 065 } 066 } 067 catch (ConverterNotFoundException ex) { 068 throw new ConversionNotSupportedException(value, requiredType, ex); 069 } 070 catch (ConversionException ex) { 071 throw new TypeMismatchException(value, requiredType, ex); 072 } 073 catch (IllegalStateException ex) { 074 throw new ConversionNotSupportedException(value, requiredType, ex); 075 } 076 catch (IllegalArgumentException ex) { 077 throw new TypeMismatchException(value, requiredType, ex); 078 } 079 } 080 081}