是否可以声明Supplier需要抛出异常?

2024-02-16

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

/**
 * 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。有没有any way我可以将其添加到方法声明中getFromConfig?

或者是像下面这样的唯一方法?

@FunctionalInterface
public interface SupplierWithIO<T> extends Supplier<T> {
    @Override
    @Deprecated
    default public T get() {
        throw new UnsupportedOperationException();
    }

    public T getWithIO() throws IOException;
}

Update,我刚刚意识到Supplier接口是一个really简单的一个,因为它只有get()方法。我延长的最初原因Supplier是保留基本功能,例如默认方法。


Edit

正如多次指出的,您不需要任何自定义类,请使用Callable and Runnable instead

错误且过时的解决方案

考虑这个通用解决方案:

// 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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以声明Supplier需要抛出异常? 的相关文章

随机推荐

  • QImage/QPixmap 大小限制?

    是否有任何已知的尺寸 空间限制QPixmap and or QImage记录的对象 我没有找到任何与此相关的有用信息 我目前在 OSX 和 Windows 上使用 Qt 4 7 3 我特别感兴趣的是 宽度 高度限制 限制取决于颜色格式 32
  • UTF-8 和 ISO-8859-1 有什么区别? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 有什么区别UTF 8 https en wikipedia org wiki UTF 8 and ISO 8859 1 https e
  • JSF:commandLink 作为 outputFormat 的参数

    我正在国际化一些 JSF 文件 因此正在外部化字符串 以及使用占位符的字符串连接 我对 JSF 的经验很少 今天和昨天 所以如果我的问题有一个明显的答案 请原谅 我一直在成功地使用 h outputFormat 标记 和 f param 标
  • 用户窗体根据屏幕分辨率调整大小

    我有一个 Excel 用户表单 我想在打开时调整大小以适应屏幕分辨率 我通过得到高度和宽度Application Height and Application Width 通常使用这两个参数和以下代码 应该可以解决问题 Me Top App
  • 以编程方式最大化窗口并防止用户更改窗口状态

    如何以编程方式最大化窗口 以便窗口一旦打开就无法调整大小 达到最大化状态 例如 最大化 Internet Explorer 并查看它 我将 FormWindowState 属性设置为 this WindowState FormWindowS
  • 检测视图中的任何触摸(iPhone SDK)

    我目前正在使用 void touchesBegan NSSet touches withEvent UIEvent event void touchesEnded NSSet touches withEvent UIEvent event
  • 在 Electron 中使用量角器

    我正在尝试为我运行的应用程序设置单元测试和 e2e 测试Electron http electron atom io using 量角器 https angular github io protractor 我参考了很多不同的帖子 this
  • Rails 渲染路线路径

    我对 Rails 还很陌生 很难理解 Rails 中路径系统的工作原理 在我的routes rb中 我创建了一个用于注册的别名 match signup gt user new resource user controller gt use
  • 数据路径 '''' 不应具有附加属性 (es5BrowserSupport)

    尝试在 Angular 中开始 在 CLI 中创建项目后 我尝试使用两者打开项目ng serve o and npm start但我收到以下错误 Schema validation failed with the following err
  • 线程与并行,它们有何不同?

    线程和并行有什么区别 哪一个比另一个有优势 Daniel Moth 我的前同事 线程 并发与并行 http www danielmoth com Blog 2008 11 threadingconcurrency vs parallelis
  • 为什么 Firefox 忽略基于范围查询的缓存控制?

    Web 服务器能够将媒体 本例中为音频 传输到浏览器 浏览器使用 HTML5 控件来播放媒体 然而 我发现 Firefox 正在缓存媒体 尽管我 相信我 明确告诉它不要这样做 我有预感 它与 206 部分内容响应有关 因为带有完整 200
  • 在分页期间获取SQL Server中记录总数的有效方法

    当查询 sql server 中的表时 我试图仅获取当前页的记录 但是 我需要为特定查询返回的记录总数来计算页数 如何在不编写另一个查询来计算记录的情况下有效地执行此操作 WITH allentities AS SELECT Row num
  • 错误 CS0106:修饰符“private”对于此项无效 Unity 中的 C# 错误

    我不断收到此错误 CS0106 修饰符 私有 对此项目无效 并且需要一些帮助 我正在尝试为我的游戏制作一个随机对象生成器 但由于我仍然是新手编码器 我似乎不知道如何解决这个问题 你能帮忙的话 我会很高兴 这是我使用的代码 using Sys
  • 谷歌地图可以根据小时分钟秒绘制点吗

    我正在尝试绘制以时分秒秒格式提供给我的 GPS 数据 GLatLng 会采用这种形式吗 还是我需要先转换它 很难在互联网上找到与此相关的任何内容 如果可以采用这种格式 我们将不胜感激 据我所知它不接受这种格式 但转换它真的很容易 只需计算一
  • Python 中的最佳 ETL 包

    我有两个用例 从 Oracle PostgreSQL Redshift S3 CSV 提取 转换并加载到我自己的 Redshift 集群 安排作业每天 每周运行 INSERT TABLE 或 INSERT NONE 选项更好 我目前正在使用
  • 如何在android中为不同类型的标记指定onMarkerclick()

    在谷歌地图上 我为不同的目的放置不同颜色的标记 在这里我想要每个标记的 onMarkerclick 具有不同的功能 例如 所有绿色标记 如何为此创造条件 这是我创建一组的代码标记数 Override public void onMapLon
  • 如何为 UIFontMetrics 指定最小 UIContentSizeCategory?

    我有一种基于动态类型创建自动缩放字体的方法 如下所示 extension UIFont public static func getAutoScalingFont fontName String textStyle UIFont TextS
  • 使用 conda env 的 apache-airflow systemd 文件

    我正在尝试奔跑apache airflow在 Ubuntu 16 04 文件上 使用 systemd 我大致跟着本教程 https github com hgrif airflow tutorial并安装 设置以下内容 Miniconda
  • Android 中打开 pdf 文件的限制

    我正在尝试从 Android 应用程序中打开一些 pdf 文件 我正在使用 Intent 来执行此操作 Intent intent new Intent intent setDataAndType Uri parse url applica
  • 是否可以声明Supplier需要抛出异常?

    所以我尝试重构以下代码 Returns the duration from the config file return The duration private Duration durationFromConfig try return