首页

关于granite源码包MapUtil关系KV键值对工具类获取反射类型、支持多场景Map的实例化

标签:granite,mapUtil,关系KV键值对工具类     发布时间:2018-05-21   

一、前言

基于granite源码包org.granite.util.MapUtil键值关系工具类,分别实现java.lang.reflect.Type组件类型方法getComponentTypes、各种场景(排序TreeMap、Hash序列HashMap及自定义实现Map等)的实例化Map的类型newMap。

二、源码说明

MapUtil类依赖org.granite.util.ClassUtil

package org.granite.util;@b@@b@import java.lang.reflect.ParameterizedType;@b@import java.lang.reflect.Type;@b@import java.lang.reflect.WildcardType;@b@import java.util.HashMap;@b@import java.util.Map;@b@import java.util.SortedMap;@b@import java.util.TreeMap;@b@@b@public class MapUtil@b@{@b@  public static Type[] getComponentTypes(Type mapType)@b@  {@b@    Class mapClass = ClassUtil.classOfType(mapType);@b@@b@    if (!(Map.class.isAssignableFrom(mapClass)))@b@      return null;@b@@b@    Type[] componentTypes = { @b@      WildcardType.class, @b@      WildcardType.class };@b@@b@    if (mapType instanceof ParameterizedType) {@b@      Type[] argTypes = ((ParameterizedType)mapType).getActualTypeArguments();@b@      if (argTypes != null) {@b@        if (argTypes.length > 0)@b@          componentTypes[0] = argTypes[0];@b@        if (argTypes.length > 1)@b@          componentTypes[1] = argTypes[1];@b@      }@b@    }@b@@b@    return componentTypes;@b@  }@b@@b@  public static Map<Object, Object> newMap(Class<?> targetClass, int length)@b@    throws InstantiationException, IllegalAccessException@b@  {@b@    if (targetClass.isInterface())@b@    {@b@      if (SortedMap.class.isAssignableFrom(targetClass))@b@        return new TreeMap();@b@@b@      if (targetClass.isAssignableFrom(HashMap.class))@b@        return new HashMap(length);@b@@b@      throw new IllegalArgumentException("Unsupported collection interface: " + targetClass);@b@    }@b@@b@    return ((Map)targetClass.newInstance());@b@  }@b@}