是否可以声明 Supplier<T> 需要引发异常?
所以我正在尝试重构以下代码:
/**
* 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
get()
Supplier