2016-01-14 11 views
5

Sto cercando di convertire questo:Java 8 farmaci generici e di inferenza problema

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

che compila bene, al più moderno Java 8 flussi versione:

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

che produce un errore messaggio:

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 

posso capire perché il compilatore avrebbe avuto problemi con questo --- non abbastanza informazioni sul tipo per capire l'i nference. Quello che non riesco a vedere è come ripararlo. Qualcuno sa?

risposta

11

Il messaggio di errore non è particolarmente chiaro ma il problema è che non si sta raccogliendo il nome dei metodi ma i metodi stessi.

In altri termini, si sta perdendo la mappatura dal Method al suo nome:

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

Scusate mancante che e grazie per segnalarlo. – user1677663

Problemi correlati