1 16 17 package org.springframework.beans.factory.config; 18 19 import java.util.ArrayList ; 20 import java.util.Iterator ; 21 import java.util.List ; 22 23 import org.springframework.beans.BeanUtils; 24 import org.springframework.beans.TypeConverter; 25 import org.springframework.core.GenericCollectionTypeResolver; 26 import org.springframework.core.JdkVersion; 27 28 37 public class ListFactoryBean extends AbstractFactoryBean { 38 39 private List sourceList; 40 41 private Class targetListClass; 42 43 44 47 public void setSourceList(List sourceList) { 48 this.sourceList = sourceList; 49 } 50 51 57 public void setTargetListClass(Class targetListClass) { 58 if (targetListClass == null) { 59 throw new IllegalArgumentException ("'targetListClass' must not be null"); 60 } 61 if (!List .class.isAssignableFrom(targetListClass)) { 62 throw new IllegalArgumentException ("'targetListClass' must implement [java.util.List]"); 63 } 64 this.targetListClass = targetListClass; 65 } 66 67 68 public Class getObjectType() { 69 return List .class; 70 } 71 72 protected Object createInstance() { 73 if (this.sourceList == null) { 74 throw new IllegalArgumentException ("'sourceList' is required"); 75 } 76 List result = null; 77 if (this.targetListClass != null) { 78 result = (List ) BeanUtils.instantiateClass(this.targetListClass); 79 } 80 else { 81 result = new ArrayList (this.sourceList.size()); 82 } 83 Class valueType = null; 84 if (this.targetListClass != null && JdkVersion.isAtLeastJava15()) { 85 valueType = GenericCollectionTypeResolver.getCollectionType(this.targetListClass); 86 } 87 if (valueType != null) { 88 TypeConverter converter = getBeanTypeConverter(); 89 for (Iterator it = this.sourceList.iterator(); it.hasNext();) { 90 result.add(converter.convertIfNecessary(it.next(), valueType)); 91 } 92 } 93 else { 94 result.addAll(this.sourceList); 95 } 96 return result; 97 } 98 99 } 100 | Popular Tags |