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.core.convert.support; 018 019import java.beans.PropertyEditorSupport; 020 021import org.springframework.core.convert.ConversionService; 022import org.springframework.core.convert.TypeDescriptor; 023import org.springframework.lang.Nullable; 024import org.springframework.util.Assert; 025 026/** 027 * Adapter that exposes a {@link java.beans.PropertyEditor} for any given 028 * {@link org.springframework.core.convert.ConversionService} and specific target type. 029 * 030 * @author Juergen Hoeller 031 * @since 3.0 032 */ 033public class ConvertingPropertyEditorAdapter extends PropertyEditorSupport { 034 035 private final ConversionService conversionService; 036 037 private final TypeDescriptor targetDescriptor; 038 039 private final boolean canConvertToString; 040 041 042 /** 043 * Create a new ConvertingPropertyEditorAdapter for a given 044 * {@link org.springframework.core.convert.ConversionService} 045 * and the given target type. 046 * @param conversionService the ConversionService to delegate to 047 * @param targetDescriptor the target type to convert to 048 */ 049 public ConvertingPropertyEditorAdapter(ConversionService conversionService, TypeDescriptor targetDescriptor) { 050 Assert.notNull(conversionService, "ConversionService must not be null"); 051 Assert.notNull(targetDescriptor, "TypeDescriptor must not be null"); 052 this.conversionService = conversionService; 053 this.targetDescriptor = targetDescriptor; 054 this.canConvertToString = conversionService.canConvert(this.targetDescriptor, TypeDescriptor.valueOf(String.class)); 055 } 056 057 058 @Override 059 public void setAsText(@Nullable String text) throws IllegalArgumentException { 060 setValue(this.conversionService.convert(text, TypeDescriptor.valueOf(String.class), this.targetDescriptor)); 061 } 062 063 @Override 064 @Nullable 065 public String getAsText() { 066 if (this.canConvertToString) { 067 return (String) this.conversionService.convert(getValue(), this.targetDescriptor, TypeDescriptor.valueOf(String.class)); 068 } 069 else { 070 return null; 071 } 072 } 073 074}