2016-01-14 69 views
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。我看不到的是如何解決它。有人知道嗎?

回答

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)); 
} 
+0

對不起,缺少謝謝你指出來。 – user1677663