5
我試圖將此轉換:Java的泛型8和類型推斷問題
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
我可以看到爲什麼編譯器會有這個麻煩---沒有足夠的類型信息來找出我nference。我看不到的是如何解決它。有人知道嗎?
對不起,缺少謝謝你指出來。 – user1677663