1 16 17 package org.springframework.beans.factory.config; 18 19 import java.util.Iterator ; 20 import java.util.Set ; 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 SetFactoryBean extends AbstractFactoryBean { 38 39 private Set sourceSet; 40 41 private Class targetSetClass; 42 43 44 47 public void setSourceSet(Set sourceSet) { 48 this.sourceSet = sourceSet; 49 } 50 51 59 public void setTargetSetClass(Class targetSetClass) { 60 if (targetSetClass == null) { 61 throw new IllegalArgumentException ("'targetSetClass' must not be null"); 62 } 63 if (!Set .class.isAssignableFrom(targetSetClass)) { 64 throw new IllegalArgumentException ("'targetSetClass' must implement [java.util.Set]"); 65 } 66 this.targetSetClass = targetSetClass; 67 } 68 69 70 public Class getObjectType() { 71 return Set .class; 72 } 73 74 protected Object createInstance() { 75 if (this.sourceSet == null) { 76 throw new IllegalArgumentException ("'sourceSet' is required"); 77 } 78 Set result = null; 79 if (this.targetSetClass != null) { 80 result = (Set ) BeanUtils.instantiateClass(this.targetSetClass); 81 } 82 else { 83 result = CollectionFactory.createLinkedSetIfPossible(this.sourceSet.size()); 84 } 85 Class valueType = null; 86 if (this.targetSetClass != null && JdkVersion.isAtLeastJava15()) { 87 valueType = GenericCollectionTypeResolver.getCollectionType(this.targetSetClass); 88 } 89 if (valueType != null) { 90 TypeConverter converter = getBeanTypeConverter(); 91 for (Iterator it = this.sourceSet.iterator(); it.hasNext();) { 92 result.add(converter.convertIfNecessary(it.next(), valueType)); 93 } 94 } 95 else { 96 result.addAll(this.sourceSet); 97 } 98 return result; 99 } 100 101 } 102 | Popular Tags |