简体   繁体   English

Java 8泛型和类型推断问题

[英]Java 8 generics and type inference issue

I'm trying to convert this: 我想转换这个:

static Set<String> methodSet(Class<?> type) {
    Set<String> result = new TreeSet<>();
    for(Method m : type.getMethods())
        result.add(m.getName());
    return result;
}

Which compiles just fine, to the more modern Java 8 streams version: 哪个编译得很好,更现代的Java 8流版本:

static Set<String> methodSet2(Class<?> type) {
    return Arrays.stream(type.getMethods())
        .collect(Collectors.toCollection(TreeSet::new));
}

Which produces an error message: 这会产生错误消息:

error: incompatible types: inference variable T has incompatible bounds
      .collect(Collectors.toCollection(TreeSet::new));
              ^
    equality constraints: String,E
    lower bounds: Method
  where T,C,E are type-variables:
    T extends Object declared in method <T,C>toCollection(Supplier<C>)
    C extends Collection<T> declared in method <T,C>toCollection(Supplier<C>)
    E extends Object declared in class TreeSet
1 error

I can see why the compiler would have trouble with this --- not enough type information to figure out the inference. 我可以看到为什么编译器会遇到这个问题 - 没有足够的类型信息来找出推论。 What I can't see is how to fix it. 我看不到的是如何解决它。 Does anyone know? 有人知道吗?

The error message is not particularly clear but the problem is that you are not collecting the name of the methods but the methods themselves. 错误消息不是特别清楚,但问题是您没有收集方法的名称,而是收集方法本身。

In other terms, you are missing the mapping from the Method to its name: 换句话说,您缺少从Method到其名称的映射:

static Set<String> methodSet2(Class<?> type) {
    return Arrays.stream(type.getMethods())
                 .map(Method::getName) // <-- maps a method to its name
                 .collect(Collectors.toCollection(TreeSet::new));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM