让我们假设以下方法(比如来自Guava的Iterables):
public static Iterable filter(final Iterable> unfiltered, final Class type) {
return null;
}
而这个集合:
Set> objs = ...;
然后编译以下代码并正确派生泛型
Iterable a2 = Iterables.filter(objs, String.class);
(在Guava中,这将返回objs中所有字符串的可迭代.)
但现在让我们假设以下类:
static class Abc {
E someField;
}
我不知道如何调用过滤器并获得Iterable< Abc>:
Iterable a3 = Iterables.filter(objs, Abc.class);
Iterable> a4 = Iterables.filter(objs, Abc.class); // Compile error - Abc and Abc> are incompatible types
Iterable> a5 = Iterables.filter(objs, Abc>.class); // Compile error
Iterable> a6 = Iterables.>filter(objs, Abc.class); // Compile error
Iterable> a7 = (Iterable>) Iterables.filter(objs, Abc.class); // Compile error - inconvertible types
Iterable> a8 = Iterables.filter(objs, new Abc>().getClass()); // Compile error
Iterable> a8a = Iterables.filter(objs, new Abc().getClass()); // Compile error
只有a3编译,但是我在Abc上没有参数,因此在后续代码中没有进行泛型类型检查.
我知道类型参数在运行时不存在,所以我不想尝试编写如下代码:
Iterable> a9 = Iterables.filter(objs, Abc.class); // Compile error
我只想过滤Abc类型的所有对象(如a3所做),但在结果中包含泛型参数.我发现这样做的唯一方法是以下,这是愚蠢的:
Iterable> a10 = new HashSet>();
for (Abc> a : Iterables.filter(objs, Abc.class)) {
((Set>)a10).add(a);
}
谢谢.