问题描述
如何遍历通配符泛型?基本上我想内联以下方法:
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);
...
}
...
这篇关于如何迭代通配符泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!