因此,我试图重构以下代码:

/**
 * Returns the duration from the config file.
 *
 * @return  The duration.
 */
private Duration durationFromConfig() {
    try {
        return durationFromConfigInner();
    } catch (IOException ex) {
        throw new IllegalStateException("The config file (\"" + configFile + "\") has not been found.");
    }
}

/**
 * Returns the duration from the config file.
 *
 * Searches the log file for the first line indicating the config entry for this instance.
 *
 * @return  The duration.
 * @throws FileNotFoundException If the config file has not been found.
 */
private Duration durationFromConfigInner() throws IOException {
    String entryKey = subClass.getSimpleName();
    configLastModified = Files.getLastModifiedTime(configFile);
    String entryValue = ConfigFileUtils.readFileEntry(configFile, entryKey);
    return Duration.of(entryValue);
}

我想出了以下几点:
private <T> T getFromConfig(final Supplier<T> supplier) {
    try {
        return supplier.get();
    } catch (IOException ex) {
        throw new IllegalStateException("The config file (\"" + configFile + "\") has not been found.");
    }
}

但是,它不会编译(显然),因为Supplier无法抛出IOException。有什么办法可以将它添加到getFromConfig的方法声明中?

还是像下面这样的唯一方法?
@FunctionalInterface
public interface SupplierWithIO<T> extends Supplier<T> {
    @Override
    @Deprecated
    default public T get() {
        throw new UnsupportedOperationException();
    }

    public T getWithIO() throws IOException;
}

更新,我才意识到Supplier接口(interface)实际上是一个真的简单接口(interface),因为它只有get()方法。我扩展Supplier的最初原因是要推销基本功能,例如默认方法。

最佳答案

在lambda邮件列表中,这是throughly discussed。如您所见,Brian Goetz在此建议替代方法是编写自己的组合器:



在那些日子里,消费者界面被称为“阻止”。

我认为这与上述Marko建议的JB Nizet's answer相符。

后来Brian explains why就是这样设计的(问题原因)

关于java - 是否可以声明Supplier <T>需要引发异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22687943/

10-09 03:41