001/* 002 * Copyright 2002-2017 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.expression.spel.support; 018 019import org.springframework.core.convert.ConversionException; 020import org.springframework.core.convert.ConversionService; 021import org.springframework.core.convert.TypeDescriptor; 022import org.springframework.core.convert.support.DefaultConversionService; 023import org.springframework.expression.TypeConverter; 024import org.springframework.expression.spel.SpelEvaluationException; 025import org.springframework.expression.spel.SpelMessage; 026import org.springframework.util.Assert; 027 028/** 029 * Default implementation of the {@link TypeConverter} interface, 030 * delegating to a core Spring {@link ConversionService}. 031 * 032 * @author Juergen Hoeller 033 * @author Andy Clement 034 * @since 3.0 035 * @see org.springframework.core.convert.ConversionService 036 */ 037public class StandardTypeConverter implements TypeConverter { 038 039 private final ConversionService conversionService; 040 041 042 /** 043 * Create a StandardTypeConverter for the default ConversionService. 044 */ 045 public StandardTypeConverter() { 046 this.conversionService = DefaultConversionService.getSharedInstance(); 047 } 048 049 /** 050 * Create a StandardTypeConverter for the given ConversionService. 051 * @param conversionService the ConversionService to delegate to 052 */ 053 public StandardTypeConverter(ConversionService conversionService) { 054 Assert.notNull(conversionService, "ConversionService must not be null"); 055 this.conversionService = conversionService; 056 } 057 058 059 @Override 060 public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) { 061 return this.conversionService.canConvert(sourceType, targetType); 062 } 063 064 @Override 065 public Object convertValue(Object value, TypeDescriptor sourceType, TypeDescriptor targetType) { 066 try { 067 return this.conversionService.convert(value, sourceType, targetType); 068 } 069 catch (ConversionException ex) { 070 throw new SpelEvaluationException(ex, SpelMessage.TYPE_CONVERSION_ERROR, 071 (sourceType != null ? sourceType.toString() : (value != null ? value.getClass().getName() : "null")), 072 targetType.toString()); 073 } 074 } 075 076}