Java 8 泛型和类型推断问题

5

我正在尝试将这个转换为:

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

这段代码可以正常编译,也可以使用更现代的Java 8流版本:

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

这会生成一个错误消息:

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

我能理解编译器为何会有困难——缺乏足够的类型信息以推断。但我不知道如何解决它。有人知道吗?

1个回答

11

错误消息并不是特别清楚,但问题在于您没有收集方法的名称,而是方法本身。

换句话说,您缺少从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));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接