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