2016-01-14 16 views
5

मैं कन्वर्ट करने के लिए इस कोशिश कर रहा हूँ:जावा 8 जेनरिक और प्रकार निष्कर्ष मुद्दा

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

कौन सा ठीक संकलित, और अधिक आधुनिक जावा 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

त्रुटि संदेश विशेष रूप से स्पष्ट नहीं है लेकिन समस्या यह है कि आप विधियों का नाम एकत्र नहीं कर रहे हैं बल्कि विधियों को स्वयं संग्रहित कर रहे हैं। लापता है कि के लिए

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

क्षमा करें और यह उनका कहना है के लिए धन्यवाद:

अन्य शब्दों में, आप अपने नाम के Method से मानचित्रण याद कर रहे हैं। – user1677663

संबंधित मुद्दे