Java中type作为参数_java – 将带有type参数的类传递给函数

让我们假设以下方法(比如来自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);

}

谢谢.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值