【发布时间】:2016-01-14 20:43:46
【问题描述】:
我正在尝试转换:
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
我明白为什么编译器会遇到这个问题 --- 没有足够的类型信息来判断推理。我看不到如何解决它。有人知道吗?
【问题讨论】:
标签: java generics java-stream type-inference