Java 8:将对象映射到方法引用时,类型推断失败

时间:2017-03-01 14:26:36

标签: java lambda functional-programming java-8 method-reference

我有一组类对象,它们在变量handlers中扩展这个抽象类:

public abstract class RequestHandler {

    public boolean handleGet(final HttpServletRequest request, final HttpServletResponse response) {
        return true;
    }

    public boolean handlePost(final HttpServletRequest request, final HttpServletResponse response) {
        return true;
    }

    public boolean handlePut(final HttpServletRequest request, final HttpServletResponse response) {
        return true;
    }

    public boolean handleDelete(final HttpServletRequest request, final HttpServletResponse response) {
        return true;
    }

    public boolean handleTrace(final HttpServletRequest request, final HttpServletResponse response) {
        return true;
    }

    public boolean handleOptions(final HttpServletRequest request, final HttpServletResponse response) {
        return true;
    }

    public boolean handleConnect(final HttpServletRequest request, final HttpServletResponse response) {
        return true;
    }

    public boolean handlePatch(final HttpServletRequest request, final HttpServletResponse response) {
        return true;
    }
}

我现在想把这个集合映射到BiFunction的列表:

    final List<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> getHandlers = Arrays.stream(handlers)
            .<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>>map(handler -> handler::handleGet)
            .collect(Collectors.toList());

如果我删除显式泛型类型规范:

    final List<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> getHandlers = Arrays.stream(handlers)
            .map(handler -> handler::handleGet)
            .collect(Collectors.toList());

我在handler::handleGet收到了编译错误:

  

对象不是功能界面

为什么编译器没有正确推断出这里的类型? 谢谢!

0 个答案:

没有答案