一、前言
基于granite源码包org.granite.util.CollectionUtil集合工具类,分别获取集合反射类型java.lang.reflect.Type、实例化newCollection各种常用集合序列类集(TreeSet/HashSet/ArrayList/自定义集合等)。
二、源码说明
CollectionUtil类依赖org.granite.util.ClassUtil
package org.granite.util;@b@@b@import java.lang.reflect.ParameterizedType;@b@import java.lang.reflect.Type;@b@import java.util.ArrayList;@b@import java.util.Collection;@b@import java.util.HashSet;@b@import java.util.Set;@b@import java.util.SortedSet;@b@import java.util.TreeSet;@b@@b@public class CollectionUtil@b@{@b@ public static Type getComponentType(Type collectionType)@b@ {@b@ Class collectionClass = ClassUtil.classOfType(collectionType);@b@ if ((collectionClass == null) || (!(Collection.class.isAssignableFrom(collectionClass))))@b@ return null;@b@@b@ if (collectionType instanceof ParameterizedType) {@b@ Type[] componentTypes = ((ParameterizedType)collectionType).getActualTypeArguments();@b@ if ((componentTypes != null) && (componentTypes.length == 1))@b@ return componentTypes[0];@b@ }@b@@b@ return Object.class;@b@ }@b@@b@ public static Collection<Object> newCollection(Class<?> targetClass, int length)@b@ throws InstantiationException, IllegalAccessException@b@ {@b@ if (targetClass.isInterface())@b@ {@b@ if (Set.class.isAssignableFrom(targetClass)) {@b@ if (SortedSet.class.isAssignableFrom(targetClass))@b@ return new TreeSet();@b@ return new HashSet(length);@b@ }@b@@b@ if (targetClass.isAssignableFrom(ArrayList.class))@b@ return new ArrayList(length);@b@@b@ throw new IllegalArgumentException("Unsupported collection interface: " + targetClass);@b@ }@b@@b@ return ((Collection)targetClass.newInstance());@b@ }@b@}