1 16 17 package org.springframework.beans.factory.config; 18 19 import java.util.Iterator ; 20 import java.util.Map ; 21 22 import org.springframework.beans.BeanUtils; 23 import org.springframework.beans.TypeConverter; 24 import org.springframework.core.CollectionFactory; 25 import org.springframework.core.GenericCollectionTypeResolver; 26 import org.springframework.core.JdkVersion; 27 28 37 public class MapFactoryBean extends AbstractFactoryBean { 38 39 private Map sourceMap; 40 41 private Class targetMapClass; 42 43 44 47 public void setSourceMap(Map sourceMap) { 48 this.sourceMap = sourceMap; 49 } 50 51 59 public void setTargetMapClass(Class targetMapClass) { 60 if (targetMapClass == null) { 61 throw new IllegalArgumentException ("'targetMapClass' must not be null"); 62 } 63 if (!Map .class.isAssignableFrom(targetMapClass)) { 64 throw new IllegalArgumentException ("'targetMapClass' must implement [java.util.Map]"); 65 } 66 this.targetMapClass = targetMapClass; 67 } 68 69 70 public Class getObjectType() { 71 return Map .class; 72 } 73 74 protected Object createInstance() { 75 if (this.sourceMap == null) { 76 throw new IllegalArgumentException ("'sourceMap' is required"); 77 } 78 Map result = null; 79 if (this.targetMapClass != null) { 80 result = (Map ) BeanUtils.instantiateClass(this.targetMapClass); 81 } 82 else { 83 result = CollectionFactory.createLinkedMapIfPossible(this.sourceMap.size()); 84 } 85 Class keyType = null; 86 Class valueType = null; 87 if (this.targetMapClass != null && JdkVersion.isAtLeastJava15()) { 88 keyType = GenericCollectionTypeResolver.getMapKeyType(this.targetMapClass); 89 valueType = GenericCollectionTypeResolver.getMapValueType(this.targetMapClass); 90 } 91 if (keyType != null || valueType != null) { 92 TypeConverter converter = getBeanTypeConverter(); 93 for (Iterator it = this.sourceMap.entrySet().iterator(); it.hasNext();) { 94 Map.Entry entry = (Map.Entry ) it.next(); 95 Object convertedKey = converter.convertIfNecessary(entry.getKey(), keyType); 96 Object convertedValue = converter.convertIfNecessary(entry.getValue(), valueType); 97 result.put(convertedKey, convertedValue); 98 } 99 } 100 else { 101 result.putAll(this.sourceMap); 102 } 103 return result; 104 } 105 106 } 107 | Popular Tags |