java - 无法从有界通配符引用中引用泛型类型

标签 java generics bounded-wildcard

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/

相关文章:

java - 上界通配符(扩展)不起作用;数组列表<? extends SuperType> 不允许子类型的实例

java - 什么是 PECS(生产者扩展消费者 super )?

java - 递归调用的返回值是多少

c# - 通用参数基类型 : "There is no implicit reference conversion from B to A"

c# - 传递和执行具有不同参数签名的函数

c# - 约束参数,new()

java - 嵌套的ArrayList初始化有问题吗?

Android 版本 4.4.4 的 java.lang.IllegalStateException

java - 并行流哈希集

java - 什么是标量类型,为什么禁止未经检查的转换为数组类型比禁止转换为标量类型的风险更大?