java - 在不检出元素的情况下获取通用类型的 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;
}
另一方面,这给了我:
?
如果无法使用反射,是否有任何其他棘手的方法来获取信息,集合是否包含任何集合而不签出第一个元素?
解决方案
不,泛型是一种使类型检查在编译时更有用的工具。它们在运行时不存在。
在运行时,一个 Collection<whatever> 只不过是一个没有更多信息的 Collection。只有它的内容描述了它所包含的内容。
推荐阅读
- python - python 3d funcanimation不绘图
- firebase - Google BigQuery 中的 Google Firebase 原始事件数据中是否有插入的日期列?
- javascript - 时间转换器网页设计
- python - 如何在 Django 中对 401、402、403 进行错误处理
- api - 如何在颤动中获取带有参数的值Http Get Request
- rust - 特征定义中的where子句是什么意思?
- python - RuntimeError: shape '[6, 1920, 8, -1]' 对于大小为 369024 的输入无效
- firebase - 如何解决注销问题 Firebase FLutter
- python - 即使其余代码工作正常,我的打印语句也会被忽略
- asp.net-core - 依赖倒置原则。为什么我可以在 ASP.NET Core 5 中访问非直接引用项目的类?