Java 8泛型和类型推断问题

时间:2016-01-14 20:43:46

标签: java generics java-stream type-inference

我试图转换它:

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

对于更现代的Java 8流版本,编译得很好:

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

会产生错误消息:

string npcs = " 20 - 10 , 30 - 40 ";

//All IDs like 20,30
var ids = npcs.Split(',').Select(c => c.Split('-').First());

//All amounts like 10,40
var amounts = npcs.Split(',').Select(c => c.Split('-').Last());

我可以看到为什么编译器会遇到这个问题---没有足够的类型信息来找出推论。我无法看到的是如何解决它。有人知道吗?

1 个答案:

答案 0 :(得分: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));
}