如何遍历通配符泛型? [英] How to iterate over a wildcard generic?
问题描述
如何遍历通配符泛型?基本上,我想内联以下方法:
How can I iterate over a wildcard generic? Basically I would like to inline the following method:
private <T extends Fact> void iterateFacts(FactManager<T> factManager) {
for (T fact : factManager) {
factManager.doSomething(fact);
}
}
如果此代码位于如图所示的单独方法中,则它可以工作,因为通用方法上下文允许定义一个可以对其进行迭代的通配符类型(此处为 T
).如果尝试内联此方法,则该方法的上下文将消失,并且无法再遍历通配符类型.即使在Eclipse中自动执行此操作,也会失败,并显示以下(不可编译)代码:
If this code is in a separate method as shown, it works because the generic method context allows to define a wildcard type (here T
) over which one can iterate. If one tries to inline this method, the method context is gone and one cannot iterate over a wildcard type anymore. Even doing this automatically in Eclipse fails with the following (uncompilable) code:
...
for (FactManager<?> factManager : factManagers) {
...
for ( fact : factManager) {
factManager.doSomething(fact);
}
...
}
...
我的问题很简单:是否有一种方法可以迭代一些通配符类型,或者这是对泛型的限制(意味着不可能这样做)?
My question is simply: Is there a way to put some wildcard type one can iterate over, or is this a limitation of generics (meaning it is impossible to do so)?
推荐答案
类型参数只能在上定义
- 类型(即类/接口)
- 方法和
- 构造函数.
您将需要一个用于本地块的类型参数,这是不可能的.
You would need a type parameter for a local block, which is not possible.
是的,有时我也会错过类似的东西.
Yeah, I missed something like this sometimes, too.
但是,这里没有内联方法并没有真正的问题-如果它在内联有所帮助的地方出现了性能瓶颈,那么Hotspot会再次内联该方法(不在乎该类型).
But there is not really a problem with having the method non-inlined here - if it presents a performance bottleneck where inlining would help, Hotspot will inline it again (not caring about the type).
另外,使用单独的方法可以为其指定一个描述性名称.
Additionally, having a separate method allows giving it a descriptive name.
只是一个想法,如果您经常需要:
Just an idea, if you need this often:
interface DoWithFM {
void <T> run(FactManager<T> t);
}
...
for (FactManager<?> factManager : factManagers) {
...
new DoWithFM() { public <T> run(FactManager<T> factManager) {
for (T fact : factManager) {
factManager.doSomething(fact);
}
}.run(factManager);
...
}
...
这篇关于如何遍历通配符泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!