一、前言
通过dozer-5.3.2.jar提供的org.dozer.util.CollectionUtils集合工具类,对是否数组isArray、是否集合isCollection、是否类集isSet、是否原始数组isPrimitiveArray、将序列转换为数组convertListToArray等等操作。
二、源码说明
package org.dozer.util;@b@@b@import java.lang.reflect.Array;@b@import java.util.ArrayList;@b@import java.util.Collection;@b@import java.util.HashSet;@b@import java.util.List;@b@import java.util.Set;@b@import java.util.SortedSet;@b@import java.util.TreeSet;@b@@b@public final class CollectionUtils@b@{@b@ public static boolean isArray(Class<?> aClass)@b@ {@b@ return aClass.isArray();@b@ }@b@@b@ public static boolean isCollection(Class<?> aClass) {@b@ return Collection.class.isAssignableFrom(aClass);@b@ }@b@@b@ public static boolean isList(Class<?> aClass) {@b@ return List.class.isAssignableFrom(aClass);@b@ }@b@@b@ public static boolean isSet(Class<?> aClass) {@b@ return Set.class.isAssignableFrom(aClass);@b@ }@b@@b@ public static boolean isPrimitiveArray(Class<?> aClass) {@b@ return ((aClass.isArray()) && (aClass.getComponentType().isPrimitive()));@b@ }@b@@b@ public static int getLengthOfCollection(Object value) {@b@ if (isArray(value.getClass()))@b@ return Array.getLength(value);@b@@b@ return ((Collection)value).size();@b@ }@b@@b@ public static Object getValueFromCollection(Object collection, int index)@b@ {@b@ if (isArray(collection.getClass()))@b@ return Array.get(collection, index);@b@@b@ return ((Collection)collection).toArray()[index];@b@ }@b@@b@ public static <T extends Set<?>> Set<?> createNewSet(Class<T> destType)@b@ {@b@ Set result;@b@ if (SortedSet.class.isAssignableFrom(destType))@b@ result = new TreeSet();@b@ else@b@ result = new HashSet();@b@@b@ return result;@b@ }@b@@b@ public static <T extends Set<?>> Set<?> createNewSet(Class<T> destSetType, Collection<?> srcValue) {@b@ Set result = createNewSet(destSetType);@b@ if (srcValue != null)@b@ result.addAll(srcValue);@b@@b@ return result;@b@ }@b@@b@ public static <T> Object convertListToArray(List<T> list, Class<T> destEntryType)@b@ {@b@ Object outArray = Array.newInstance(destEntryType, list.size());@b@ int count = 0;@b@ int size = list.size();@b@ for (int i = 0; i < size; ++i) {@b@ Object element = list.get(i);@b@ Array.set(outArray, count, element);@b@ ++count;@b@ }@b@ if (destEntryType.isPrimitive())@b@ return outArray;@b@@b@ return ((Object[])(Object[])outArray);@b@ }@b@@b@ public static List<Object> convertPrimitiveArrayToList(Object primitiveArray) {@b@ int length = Array.getLength(primitiveArray);@b@ List result = new ArrayList(length);@b@@b@ for (int i = 0; i < length; ++i)@b@ result.add(Array.get(primitiveArray, i));@b@@b@ return result;@b@ }@b@}