1 16 17 package org.springframework.beans.propertyeditors; 18 19 import java.beans.PropertyEditorSupport ; 20 import java.util.Iterator ; 21 import java.util.Map ; 22 import java.util.SortedMap ; 23 import java.util.TreeMap ; 24 25 import org.springframework.core.CollectionFactory; 26 27 36 public class CustomMapEditor extends PropertyEditorSupport { 37 38 private final Class mapType; 39 40 private final boolean nullAsEmptyMap; 41 42 43 53 public CustomMapEditor(Class mapType) { 54 this(mapType, false); 55 } 56 57 75 public CustomMapEditor(Class mapType, boolean nullAsEmptyMap) { 76 if (mapType == null) { 77 throw new IllegalArgumentException ("Map type is required"); 78 } 79 if (!Map .class.isAssignableFrom(mapType)) { 80 throw new IllegalArgumentException ( 81 "Map type [" + mapType.getName() + "] does not implement [java.util.Map]"); 82 } 83 this.mapType = mapType; 84 this.nullAsEmptyMap = nullAsEmptyMap; 85 } 86 87 88 91 public void setAsText(String text) throws IllegalArgumentException { 92 setValue(text); 93 } 94 95 98 public void setValue(Object value) { 99 if (value == null && this.nullAsEmptyMap) { 100 super.setValue(createMap(this.mapType, 0)); 101 } 102 else if (value == null || (this.mapType.isInstance(value) && !alwaysCreateNewMap())) { 103 super.setValue(value); 105 } 106 else if (value instanceof Map ) { 107 Map source = (Map ) value; 109 Map target = createMap(this.mapType, source.size()); 110 for (Iterator it = source.entrySet().iterator(); it.hasNext();) { 111 Map.Entry entry = (Map.Entry ) it.next(); 112 target.put(convertKey(entry.getKey()), convertValue(entry.getValue())); 113 } 114 super.setValue(target); 115 } 116 else { 117 throw new IllegalArgumentException ("Value cannot be converted to Map: " + value); 118 } 119 } 120 121 128 protected Map createMap(Class mapType, int initialCapacity) { 129 if (!mapType.isInterface()) { 130 try { 131 return (Map ) mapType.newInstance(); 132 } 133 catch (Exception ex) { 134 throw new IllegalArgumentException ( 135 "Could not instantiate map class [" + mapType.getName() + "]: " + ex.getMessage()); 136 } 137 } 138 else if (SortedMap .class.equals(mapType)) { 139 return new TreeMap (); 140 } 141 else { 142 return CollectionFactory.createLinkedMapIfPossible(initialCapacity); 143 } 144 } 145 146 154 protected boolean alwaysCreateNewMap() { 155 return false; 156 } 157 158 171 protected Object convertKey(Object key) { 172 return key; 173 } 174 175 188 protected Object convertValue(Object value) { 189 return value; 190 } 191 192 193 197 public String getAsText() { 198 return null; 199 } 200 201 } 202 | Popular Tags |