Class A
有什么问题吗?下面不允许它编译?
public class GenericsHell {
interface Shape{}
interface Circle extends Shape {}
interface ShapeHelper<T extends Shape> {
void draw(T shape);
}
class A<T extends Shape> {
A(T shape, ShapeHelper<? extends Shape> helper) {
helper.draw(shape); // Issues not-applicable argument error
}
}
class B {
B(Circle circle, ShapeHelper<Circle> helper) {
helper.draw(circle);
}
}
}
Eclipse 出现以下错误:
The method draw(capture#1-of ? extends Shape) in the type ShapeHelper<capture#1-of ? extends Shape> is not applicable for the arguments (T)
最佳答案
您将 A 类的通用参数定义为一件事,但随后尝试在构造函数中以不兼容的方式使用它( <T extends Shape>
与 <? extends Shape>
不同。要让代码编译,请更改它一致地使用您已经定义的通用参数:
class A<T extends Shape> {
public A(T shape, ShapeHelper<T> helper) {
helper.draw(shape);
}
}
顺便说一句,您的代码不会生成您在问题中显示的错误消息。相反,它会更像这样:
The method draw(capture#1-of ? extends GenericsHell.Shape) in the type GenericsHell.ShapeHelper is not applicable for the arguments (T)
关于java - 无法从有界通配符引用中引用泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8962078/