首页 > 解决方案 > 在不检出元素的情况下获取通用类型的 Collection

问题描述

我需要找出 a 的泛型类型Collection<?>。唯一的限制是由于我的缓存机制,我不能撤回第一个元素(如果它包含任何元素) - 所以我不能执行以下操作,因为它实际上获得了第一个值:

collection.iterator().next().getClass();

我的目标是确定,Collection<?>里面是否包含任何其他集合,例如Collection<List<List<String>>>是合格的,而 Collection 不是。我Collection<?>从作为参数传递的方法调用中接收到这个。我尝试了以下方法:

@Override
public Collection<?> execute(Collection<?> collection) {
    Class<?> clazz = collection.getClass();
    Type genericSuperClass = clazz.getGenericSuperclass();
    ParameterizedType parametrizedType = (ParameterizedType) genericSuperClass;
    Type[] typeArguments = parametrizedType.getActualTypeArguments();
    String clazzName = typeArguments[0].toString();

    // ... irrelevant code
    return null;
}

可悲的是,结果String clazzName不是java.util.List<java.util.List<java.lang.Integer>>以下内容:

我的另一个尝试是从声明的字段中获取它。

@Override
public Collection<?> execute(Collection<?> collection) {
    this.collection= collection;
    try {               
        Field field = Foo.class.getDeclaredField("collection");
        ParameterizedType parametrizedType = (ParameterizedType) field.getGenericType();
        Type type = parametrizedType .getActualTypeArguments()[0];
    } catch ( SecurityException | NoSuchFieldException e) { ... }

    // ... irrelevant code
    return null;
}

另一方面,这给了我:

?


如果无法使用反射,是否有任何其他棘手的方法来获取信息,集合是否包含任何集合而不签出第一个元素?

标签: javagenericsreflection

解决方案


不,泛型是一种使类型检查在编译时更有用的工具。它们在运行时不存在。

在运行时,一个 Collection<whatever> 只不过是一个没有更多信息的 Collection。只有它的内容描述了它所包含的内容。


推荐阅读