2016-01-14 26 views
5

Tôi đang cố gắng để chuyển đổi này suy luận:Java 8 Generics và loại vấn đề

static Set<String> methodSet(Class<?> type) { 
    Set<String> result = new TreeSet<>(); 
    for(Method m : type.getMethods()) 
     result.add(m.getName()); 
    return result; 
} 

nào biên dịch tốt, đến hiện đại hơn Java 8 suối phiên bản:

static Set<String> methodSet2(Class<?> type) { 
    return Arrays.stream(type.getMethods()) 
     .collect(Collectors.toCollection(TreeSet::new)); 
} 

nào tạo ra một lỗi tin nhắn:

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 

Tôi có thể thấy lý do tại sao trình biên dịch sẽ gặp rắc rối với thông tin này --- không đủ loại để tìm ra nference. Những gì tôi không thể nhìn thấy là làm thế nào để sửa chữa nó. Có ai biết không?

Trả lời

11

Thông báo lỗi không rõ ràng nhưng vấn đề là bạn không thu thập tên của các phương thức mà chính là các phương thức.

Nói cách khác, bạn đang thiếu ánh xạ từ Method tên của nó:

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

Xin lỗi vì thiếu điều đó và cảm ơn bạn đã trỏ nó ra. – user1677663

Các vấn đề liên quan