【发布时间】:2021-08-06 17:52:47
【问题描述】:
在 Java 中是否可以缩小泛型类的子类中的泛型类型? 我的情况是这样的:
class C<T> {
protected T foo() {...}
protected void bar(Supplier<T> foobar) {...}
}
class A<T extends B> extends C<T> {
public void someMethod(){
B b = foo(); // Compiler does not complain
bar(() -> createB()); // Compiler complains with "Type mismatch: cannot convert from B to T"
}
}
也许我所做的完全是愚蠢的,但我不明白为什么编译器不抱怨 foo(),而是抱怨 bar()。
非常感谢任何有关如何执行此操作或为什么不执行此操作的建议 :)
亲切的问候, 托马斯
【问题讨论】:
-
createB和B在哪里? -
T是B,但B不一定是T。class D extends B {}在第二种情况下中断,但显然您可以将D分配给B。 -
天哪,你说的太对了。为了解决这个问题,“createB()”也必须是 T 类型的泛型!非常感谢!