java - 泛型:通配符类型的编译错误

标签 java generics guava java-7

我已经切换到 Java 7 build 21 并开始出现奇怪的编译错误。例如,下面的代码片段无法编译(尽管 IntelliJ 未显示任何错误):

    1 Iterable<?> parts = ImmutableList.<String>of("one", "two");
    2 Function<?, String> function = new Function<Object, String>() {
    3    @Override
    4    public String apply(final Object input) {
    5        return input.toString();
    6    }
    7 };
    8 Iterable<String> result = Iterables.transform(parts, function);
    9 System.out.println(result);

但是如果我将第 2 行中的 ? 替换为 Object

    2 Function<Object, String> function = new Function<Object, String>() {

然后编译成功。

我得到的错误有点神秘:

error: method transform in class Iterables cannot be applied to given types;
required: Iterable<F>,Function<? super F,? extends T> 
found: Iterable<CAP#1>,Function<CAP#2,String> 
reason: no instance(s) of type variable(s) F,T exist so that argument type Function<CAP#2,String>
conforms to formal parameter type Function<? super F,? extends T> 
where F,T are type-variables:
F extends Object declared in method <F,T>transform(Iterable<F>,Function<? super F,? extends T>) 
T extends Object declared in method <F,T>transform(Iterable<F>,Function<? super F,? extends T>) 
where CAP#1,CAP#2 are fresh type-variables: 
CAP#1 extends Object from capture of ?
CAP#2 extends Object from capture of ? extends Object

将第 2 行更改为

    2 Function<? extends Object, String> function = new Function<Object, String>() {

没有效果。

我正在使用 JDK 1.7.0_11-b21;这用于构建 4 编译正常。

这是 javac 错误还是我的?

最佳答案

方法签名是:

<F,T> Iterable<T> transform(Iterable<F> fromIterable, Function<? super F,? extends T> function) 

这对于类型参数 F 意味着什么:

Iterable<F> :
    F can be any type here, but will influence the type parameter to Function
Function<? super F, ? extends T> :
    the first type parameter (? super F) MUST be a supertype of F

当你输入时:

Iterable<?>
Function<?, String>

你说的是 Iterable 任何东西,所以它可能是例如Iterable<Integer> . 你也在说从任何东西到字符串的函数,所以它可能是例如Function<String, String> . 由于 String 不是 Integer 的父类(super class),因此您没有满足 (? super F)条件。

关于java - 泛型:通配符类型的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14441545/

相关文章:

java - 如何在 Qulice 中禁用重复依赖项检查?

java - 如何从一个restful web服务中获取一些数据,并将其保存到数据库中?

angular - 作为 Angular2 组件的 Typescript 泛型类

java - 最佳实践 : Unit testing a method that takes in a Socket as an argument?

Java MySQL 批量插入与正常

java - 访问泛型类的静态方法

java - 对象类型的隐式声明和显式泛型声明之间的区别

java - map 和 ImmutableMap 的区别

Java 8 循环使用 com.google.common.collect.Iterables.partition 的方法?

java - google-guava MapMaker .softValues() - 值没有得到 GC-ed,OOME : HeapSpace follows