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.propertyeditors; 018 019import java.beans.PropertyEditorSupport; 020import java.lang.reflect.Array; 021import java.util.ArrayList; 022import java.util.Collection; 023import java.util.LinkedHashSet; 024import java.util.List; 025import java.util.SortedSet; 026import java.util.TreeSet; 027 028/** 029 * Property editor for Collections, converting any source Collection 030 * to a given target Collection type. 031 * 032 * <p>By default registered for Set, SortedSet and List, 033 * to automatically convert any given Collection to one of those 034 * target types if the type does not match the target property. 035 * 036 * @author Juergen Hoeller 037 * @since 1.1.3 038 * @see java.util.Collection 039 * @see java.util.Set 040 * @see java.util.SortedSet 041 * @see java.util.List 042 */ 043public class CustomCollectionEditor extends PropertyEditorSupport { 044 045 @SuppressWarnings("rawtypes") 046 private final Class<? extends Collection> collectionType; 047 048 private final boolean nullAsEmptyCollection; 049 050 051 /** 052 * Create a new CustomCollectionEditor for the given target type, 053 * keeping an incoming {@code null} as-is. 054 * @param collectionType the target type, which needs to be a 055 * sub-interface of Collection or a concrete Collection class 056 * @see java.util.Collection 057 * @see java.util.ArrayList 058 * @see java.util.TreeSet 059 * @see java.util.LinkedHashSet 060 */ 061 @SuppressWarnings("rawtypes") 062 public CustomCollectionEditor(Class<? extends Collection> collectionType) { 063 this(collectionType, false); 064 } 065 066 /** 067 * Create a new CustomCollectionEditor for the given target type. 068 * <p>If the incoming value is of the given type, it will be used as-is. 069 * If it is a different Collection type or an array, it will be converted 070 * to a default implementation of the given Collection type. 071 * If the value is anything else, a target Collection with that single 072 * value will be created. 073 * <p>The default Collection implementations are: ArrayList for List, 074 * TreeSet for SortedSet, and LinkedHashSet for Set. 075 * @param collectionType the target type, which needs to be a 076 * sub-interface of Collection or a concrete Collection class 077 * @param nullAsEmptyCollection whether to convert an incoming {@code null} 078 * value to an empty Collection (of the appropriate type) 079 * @see java.util.Collection 080 * @see java.util.ArrayList 081 * @see java.util.TreeSet 082 * @see java.util.LinkedHashSet 083 */ 084 @SuppressWarnings("rawtypes") 085 public CustomCollectionEditor(Class<? extends Collection> collectionType, boolean nullAsEmptyCollection) { 086 if (collectionType == null) { 087 throw new IllegalArgumentException("Collection type is required"); 088 } 089 if (!Collection.class.isAssignableFrom(collectionType)) { 090 throw new IllegalArgumentException( 091 "Collection type [" + collectionType.getName() + "] does not implement [java.util.Collection]"); 092 } 093 this.collectionType = collectionType; 094 this.nullAsEmptyCollection = nullAsEmptyCollection; 095 } 096 097 098 /** 099 * Convert the given text value to a Collection with a single element. 100 */ 101 @Override 102 public void setAsText(String text) throws IllegalArgumentException { 103 setValue(text); 104 } 105 106 /** 107 * Convert the given value to a Collection of the target type. 108 */ 109 @Override 110 public void setValue(Object value) { 111 if (value == null && this.nullAsEmptyCollection) { 112 super.setValue(createCollection(this.collectionType, 0)); 113 } 114 else if (value == null || (this.collectionType.isInstance(value) && !alwaysCreateNewCollection())) { 115 // Use the source value as-is, as it matches the target type. 116 super.setValue(value); 117 } 118 else if (value instanceof Collection) { 119 // Convert Collection elements. 120 Collection<?> source = (Collection<?>) value; 121 Collection<Object> target = createCollection(this.collectionType, source.size()); 122 for (Object elem : source) { 123 target.add(convertElement(elem)); 124 } 125 super.setValue(target); 126 } 127 else if (value.getClass().isArray()) { 128 // Convert array elements to Collection elements. 129 int length = Array.getLength(value); 130 Collection<Object> target = createCollection(this.collectionType, length); 131 for (int i = 0; i < length; i++) { 132 target.add(convertElement(Array.get(value, i))); 133 } 134 super.setValue(target); 135 } 136 else { 137 // A plain value: convert it to a Collection with a single element. 138 Collection<Object> target = createCollection(this.collectionType, 1); 139 target.add(convertElement(value)); 140 super.setValue(target); 141 } 142 } 143 144 /** 145 * Create a Collection of the given type, with the given 146 * initial capacity (if supported by the Collection type). 147 * @param collectionType a sub-interface of Collection 148 * @param initialCapacity the initial capacity 149 * @return the new Collection instance 150 */ 151 @SuppressWarnings({ "rawtypes", "unchecked" }) 152 protected Collection<Object> createCollection(Class<? extends Collection> collectionType, int initialCapacity) { 153 if (!collectionType.isInterface()) { 154 try { 155 return collectionType.newInstance(); 156 } 157 catch (Throwable ex) { 158 throw new IllegalArgumentException( 159 "Could not instantiate collection class: " + collectionType.getName(), ex); 160 } 161 } 162 else if (List.class == collectionType) { 163 return new ArrayList<Object>(initialCapacity); 164 } 165 else if (SortedSet.class == collectionType) { 166 return new TreeSet<Object>(); 167 } 168 else { 169 return new LinkedHashSet<Object>(initialCapacity); 170 } 171 } 172 173 /** 174 * Return whether to always create a new Collection, 175 * even if the type of the passed-in Collection already matches. 176 * <p>Default is "false"; can be overridden to enforce creation of a 177 * new Collection, for example to convert elements in any case. 178 * @see #convertElement 179 */ 180 protected boolean alwaysCreateNewCollection() { 181 return false; 182 } 183 184 /** 185 * Hook to convert each encountered Collection/array element. 186 * The default implementation simply returns the passed-in element as-is. 187 * <p>Can be overridden to perform conversion of certain elements, 188 * for example String to Integer if a String array comes in and 189 * should be converted to a Set of Integer objects. 190 * <p>Only called if actually creating a new Collection! 191 * This is by default not the case if the type of the passed-in Collection 192 * already matches. Override {@link #alwaysCreateNewCollection()} to 193 * enforce creating a new Collection in every case. 194 * @param element the source element 195 * @return the element to be used in the target Collection 196 * @see #alwaysCreateNewCollection() 197 */ 198 protected Object convertElement(Object element) { 199 return element; 200 } 201 202 203 /** 204 * This implementation returns {@code null} to indicate that 205 * there is no appropriate text representation. 206 */ 207 @Override 208 public String getAsText() { 209 return null; 210 } 211 212}