欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

java 集合反射_关于granite源码包CollectionUtil集合工具类获取集合反射类型、实例化各种集合类型HashSet/ArrayList等...

发布时间:2025/3/20 编程问答 29 豆豆
生活随笔 收集整理的这篇文章主要介绍了 java 集合反射_关于granite源码包CollectionUtil集合工具类获取集合反射类型、实例化各种集合类型HashSet/ArrayList等... 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

一、前言

基于granite源码包org.granite.util.CollectionUtil集合工具类,分别获取集合反射类型java.lang.reflect.Type、实例化newCollection各种常用集合序列类集(TreeSet/HashSet/ArrayList/自定义集合等)。

二、源码说明package org.granite.util;@b@@b@import java.lang.reflect.ParameterizedType;@b@import java.lang.reflect.Type;@b@import java.util.ArrayList;@b@import java.util.Collection;@b@import java.util.HashSet;@b@import java.util.Set;@b@import java.util.SortedSet;@b@import java.util.TreeSet;@b@@b@public class CollectionUtil@b@{@b@  public static Type getComponentType(Type collectionType)@b@  {@b@    Class collectionClass = ClassUtil.classOfType(collectionType);@b@    if ((collectionClass == null) || (!(Collection.class.isAssignableFrom(collectionClass))))@b@      return null;@b@@b@    if (collectionType instanceof ParameterizedType) {@b@      Type[] componentTypes = ((ParameterizedType)collectionType).getActualTypeArguments();@b@      if ((componentTypes != null) && (componentTypes.length == 1))@b@        return componentTypes[0];@b@    }@b@@b@    return Object.class;@b@  }@b@@b@  public static Collection newCollection(Class> targetClass, int length)@b@    throws InstantiationException, IllegalAccessException@b@  {@b@    if (targetClass.isInterface())@b@    {@b@      if (Set.class.isAssignableFrom(targetClass)) {@b@        if (SortedSet.class.isAssignableFrom(targetClass))@b@          return new TreeSet();@b@        return new HashSet(length);@b@      }@b@@b@      if (targetClass.isAssignableFrom(ArrayList.class))@b@        return new ArrayList(length);@b@@b@      throw new IllegalArgumentException("Unsupported collection interface: " + targetClass);@b@    }@b@@b@    return ((Collection)targetClass.newInstance());@b@  }@b@}

总结

以上是生活随笔为你收集整理的java 集合反射_关于granite源码包CollectionUtil集合工具类获取集合反射类型、实例化各种集合类型HashSet/ArrayList等...的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。