【问题标题】:Java 8 generics and type inference issueJava 8 泛型和类型推断问题
【发布时间】:2016-01-14 20:43:46
【问题描述】:

我正在尝试转换:

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

我明白为什么编译器会遇到这个问题 --- 没有足够的类型信息来判断推理。我看不到如何解决它。有人知道吗?

【问题讨论】:

    标签: java generics java-stream type-inference


    【解决方案1】:

    错误信息不是特别清楚,但问题是您收集的不是方法的名称而是方法本身。

    换句话说,您缺少从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));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      相关资源
      最近更新 更多