java - 是否可以声明 Supplier<T> 需要抛出异常?

标签 java java-8 functional-interface

所以我正在尝试重构以下代码:

/**
 * 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 的最初原因是为了破坏基本功能,例如默认方法。

最佳答案

编辑

正如多次指出的那样,您不需要任何自定义类,请改用 CallableRunnable

错误、过时的解决方案

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/

相关文章:

Java 8 : Expecting a stackmap frame at branch target 65

java - 如何将 java.time.Duration 映射到 XML

java - 使用FunctionalInterface/MethodReference参数对调用进行 stub /验证

java - 从 Function<V, R> 使用 compose() 或 andThen() 时返回对象

java - lambda 实际上是一个匿名类吗?

java - Gradle错误: Error:Error converting bytecode to dex: Cause: java. lang.RuntimeException:异常解析类

java - 如何在 Beanshell PostProcessor 中获取一个或多个 Http 采样器响应

java - 如何使用 VTD-XML 多次添加 xml 节点?

java - 当我从外部类调用它时,为什么会收到 ClassNotFoundException?

java - 为什么Java 8的Function.identity()的返回类型与其输入类型相同?