加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

使用反射对bean的collection属性赋值

发布时间:2020-12-14 03:21:19 所属栏目:大数据 来源:网络整理
导读:反射对bean的collection属性赋值 对collection使用反射创建时会遇到不知道具体实现类型而烦恼 比如: class School{ private List classes ; //班级列表 public void setClasses(List classes){ this.classes=classes; } pulbic List getClasses(){ return t
反射对bean的collection属性赋值

对collection使用反射创建时会遇到不知道具体实现类型而烦恼

比如:

class School{
                private List classes ; //班级列表

                public void setClasses(List classes){
                    this.classes=classes;
                }

                pulbic List getClasses(){
                    return this classes;
                }
     }

Class<?>  schoolClazz=Class.forName(School.class.getTypeName());
schoolClazz.getMethod("setClasses",argsClass);
//这里argsClass应该是具体的实现类  很明确这里是需要Arraylist 但是如果是这样代码
 class School{
                private Collection classes ; //班级列表

                public void setClasses(Collection classes){
                    this.classes=classes;
                }

                pulbic Collection getClasses(){
                    return this classes;
                }
     }
//惨了 不知道实现类是什么了  应该是ArrayList.class 还是 HashSet.class ?

没办法了?

参考下spring里面的代码:
public static <E> Collection<E> createCollection(Class<?> collectionType,@Nullable Class<?> elementType,int capacity) {
    Assert.notNull(collectionType,"Collection type must not be null");
    if (collectionType.isInterface()) {
        if (Set.class == collectionType || Collection.class == collectionType) {
            return new LinkedHashSet<>(capacity);
        }
        else if (List.class == collectionType) {
            return new ArrayList<>(capacity);
        }
        else if (SortedSet.class == collectionType || NavigableSet.class == collectionType) {
            return new TreeSet<>();
        }
        else {
            throw new IllegalArgumentException("Unsupported Collection interface: " + collectionType.getName());
        }
    }
    else if (EnumSet.class == collectionType) {
        Assert.notNull(elementType,"Cannot create EnumSet for unknown element type");
        // Cast is necessary for compilation in Eclipse 4.4.1.
        return (Collection<E>) EnumSet.noneOf(asEnumType(elementType));
    }
    else {
        if (!Collection.class.isAssignableFrom(collectionType)) {
            throw new IllegalArgumentException("Unsupported Collection type: " + collectionType.getName());
        }
        try {
            return (Collection<E>) ReflectionUtils.accessibleConstructor(collectionType).newInstance();
        }
        catch (Throwable ex) {
            throw new IllegalArgumentException(
                "Could not instantiate Collection type: " + collectionType.getName(),ex);
        }
    }
}
这里返回了具体的实现类  直接使用它的返回的具体实现类

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读