所以我正在尝试重构以下代码:
/**
* 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
的最初原因是为了破坏基本功能,例如默认方法。
最佳答案
编辑
正如多次指出的那样,您不需要任何自定义类,请改用 Callable 和 Runnable
错误、过时的解决方案
Consider this generic solution:
// We need to describe supplier which can throw exceptions @FunctionalInterface public interface ThrowingSupplier<T> { T get() throws Exception; } // Now, wrapper private <T> T callMethod(ThrowingSupplier<T> supplier) { try { return supplier.get(); } catch (Exception e) { throw new RuntimeException(e); } return null; } // And usage example String methodThrowsException(String a, String b, String c) throws Exception { // do something } String result = callMethod(() -> methodThrowsException(x, y, z));
关于java - 是否可以声明 Supplier<T> 需要抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22687943/