我正在尝试重构以下代码:
/**
* 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
的原因是为了保留基本功能,例如默认方法。
uncheckedCall
和sneakyThrow
是什么? - skiwi