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