我正在尝试将这个转换为:
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
我能理解编译器为何会有困难——缺乏足够的类型信息以推断。但我不知道如何解决它。有人知道吗?