2016-01-14 11 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 

コンパイラはこれで問題があるだろう、なぜ私が見ることができる---十分ではない種類の情報を、私を把握します言葉私が見ることができないのは、それを修正する方法です。誰か知っていますか?

答えて

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

関連する問題