001 /**
002 * GRANITE DATA SERVICES
003 * Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S.
004 *
005 * This file is part of the Granite Data Services Platform.
006 *
007 * Granite Data Services is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * Granite Data Services is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
015 * General Public License for more details.
016 *
017 * You should have received a copy of the GNU Lesser General Public
018 * License along with this library; if not, write to the Free Software
019 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
020 * USA, or see <http://www.gnu.org/licenses/>.
021 */
022 package org.granite.util;
023
024 import java.lang.reflect.ParameterizedType;
025 import java.lang.reflect.Type;
026 import java.util.ArrayList;
027 import java.util.Collection;
028 import java.util.HashSet;
029 import java.util.Set;
030 import java.util.SortedSet;
031 import java.util.TreeSet;
032
033 /**
034 * @author Franck WOLFF
035 */
036 public class CollectionUtil {
037
038 public static Type getComponentType(Type collectionType) {
039
040 Class<?> collectionClass = TypeUtil.classOfType(collectionType);
041 if (collectionClass == null || !Collection.class.isAssignableFrom(collectionClass))
042 return null;
043
044 if (collectionType instanceof ParameterizedType) {
045 Type[] componentTypes = ((ParameterizedType)collectionType).getActualTypeArguments();
046 if (componentTypes != null && componentTypes.length == 1)
047 return componentTypes[0];
048 }
049
050 return Object.class;
051 }
052
053 @SuppressWarnings("unchecked")
054 public static Collection<Object> newCollection(Class<?> targetClass, int length)
055 throws InstantiationException, IllegalAccessException {
056
057 if (targetClass.isInterface()) {
058
059 if (Set.class.isAssignableFrom(targetClass)) {
060 if (SortedSet.class.isAssignableFrom(targetClass))
061 return new TreeSet<Object>();
062 return new HashSet<Object>(length);
063 }
064
065 if (targetClass.isAssignableFrom(ArrayList.class))
066 return new ArrayList<Object>(length);
067
068 throw new IllegalArgumentException("Unsupported collection interface: " + targetClass);
069 }
070
071 return (Collection<Object>)targetClass.newInstance();
072 }
073 }