我真的需要一些帮助。 这是我的功能界面:

/**
 * This class represents a filter.
 */
@FunctionalInterface
interface FileFilter {
    /**
     * This method gets a file path and filters it in some method.
     * @return a list of the remaining files after this filter.
     * @throws IOException
     */
    abstract boolean filter(Path path) throws IOException;
}

这是拉姆达function我写:

    static FileFilter modeFilter(String value, boolean containsNo, Predicate<Path> pathMethod)
    throws IOException{
        if (value.equals(YES)) {
            if (containsNo) {
                return path -> !pathMethod.test(path);
            } else {
                return path -> pathMethod.test(path);
            }
        }

        if (containsNo) {
            return path -> pathMethod.test(path);
        }
        return path -> !pathMethod.test(path);
    }

我给过滤器这个参数:

Filters.modeFilter(commandParts[1], containsNOT, x -> Files.isHidden(x))

问题是,我得到了一个Files.isHidden错误compliation,指出存在错误时抛出未被处理 - IOExeption。

我确信,调用modeFilter抛出IOException异常的方法,所以这是没有问题的。 我该如何解决这个问题?

谢谢。

分析解答

你的方法采用Predicate<Path>作为参数。

谓词function的签名

boolean test(T)

Files.isHidden的签名

boolean isHidden(Path path) throws IOException

因此,他们不匹配:一个谓语不应该抛出IOException,但Files.isHidden()可以。

解决方案:通过一个的FileFilter作为参数,而不是Predicate<File>,因为FileFilter存在的唯一理由正是如此,它可以抛出IOException,不像谓词。

请注意,modeFilter方法没有理由抛出IOException:它所做的就是创建一个的FileFilter。它永远不会调用它。因此,它不可能抛出IOException。