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 */
022package org.granite.util;
023
024import java.lang.reflect.ParameterizedType;
025import java.lang.reflect.Type;
026import java.lang.reflect.WildcardType;
027import java.util.HashMap;
028import java.util.Map;
029import java.util.SortedMap;
030import java.util.TreeMap;
031
032/**
033 * @author Franck WOLFF
034 */
035public class MapUtil {
036
037    public static Type[] getComponentTypes(Type mapType) {
038        final Class<?> mapClass = TypeUtil.classOfType(mapType);
039
040        if (!Map.class.isAssignableFrom(mapClass))
041            return null;
042
043        Type[] componentTypes = new Type[] {
044            WildcardType.class,
045            WildcardType.class
046        };
047
048        if (mapType instanceof ParameterizedType) {
049            Type[] argTypes = ((ParameterizedType)mapType).getActualTypeArguments();
050            if (argTypes != null) {
051                if (argTypes.length > 0)
052                    componentTypes[0] = argTypes[0];
053                if (argTypes.length > 1)
054                    componentTypes[1] = argTypes[1];
055            }
056        }
057
058        return componentTypes;
059    }
060
061    @SuppressWarnings("unchecked")
062    public static Map<Object, Object> newMap(Class<?> targetClass, int length)
063        throws InstantiationException, IllegalAccessException  {
064
065        if (targetClass.isInterface()) {
066
067            if (SortedMap.class.isAssignableFrom(targetClass))
068                return new TreeMap<Object, Object>();
069
070            if (targetClass.isAssignableFrom(HashMap.class))
071                return new HashMap<Object, Object>(length);
072
073            throw new IllegalArgumentException("Unsupported collection interface: " + targetClass);
074        }
075
076        return (Map<Object, Object>)targetClass.newInstance();
077    }
078}