【问题标题】:Why undefined generic parameter of variable drops explicit generic parameter of it's method's return type?为什么变量的未定义泛型参数会丢弃其方法返回类型的显式泛型参数?
【发布时间】:2013-06-18 03:22:47
【问题描述】:
public abstract class A<T> {
    public static void test(A i) { for (String s : i.get()) {} }
    public abstract Iterable<String> get();
}

为什么我得到上面的代码:

incompatible types
required: String
found:    Object

但是如果我将test 方法的参数更改为A&lt;Object&gt;,它会编译好吗?为什么变量的未定义泛型参数会丢弃其方法返回类型的显式泛型参数?

【问题讨论】:

  • public void test(A&lt;T&gt; i) { for (String s : i.get()) {} }
  • @TheNewIdiot 这是一个静态方法。
  • 好的,那就是public static void test(A&lt;?&gt; i) { for (String s : i.get()) {} }

标签: java generics


【解决方案1】:

为什么变量的未定义泛型参数会丢弃其方法返回类型的显式泛型参数?

A 是一个 原始 类型。这是一种在 API 中删除了 所有 个泛型的类型,即使是具有固定类型参数的类型。

请参阅JLS section 4.8Raw Types section of the Java Generics FAQ 了解更多信息。

在这种情况下,如果你想要 any A,你可以使用通配符:

public static void test(A<?> i)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
相关资源
最近更新 更多