假設(shè)您有一個(gè)公開下一個(gè)接口的第 3 方庫。interface Mapper { String doMap(String input) throws CheckedException;}class CheckedException extends Exception {}我知道檢查異常在 Java 中通常是一種不好的做法,但是這段代碼來自第三方,我無法修改它。我想將 Mapper 接口的實(shí)現(xiàn)與 Java8 流 API 結(jié)合使用。考慮下面的示例實(shí)現(xiàn)。class MapperImpl implements Mapper { public String doMap(String input) throws CheckedException { return input; }}例如,現(xiàn)在,我想將映射器應(yīng)用于字符串集合。public static void main(String[] args) { List<String> strings = Arrays.asList("foo", "bar", "baz"); Mapper mapper = new MapperImpl(); List<String> mappedStrings = strings .stream() .map(mapper::doMap) .collect(Collectors.toList());}代碼無法編譯,因?yàn)?Function 不知道如何處理由 doMap 聲明的 CheckedException。我想出了兩種可能的解決方案。解決方案#1 - 包裝調(diào)用.map(value -> { try { return mapper.doMap(value); } catch (CheckedException e) { throw new UncheckedException(); } })解決方案#2 - 編寫一個(gè)實(shí)用方法public static final String uncheck (Mapper mapper, String input){ try { return mapper.doMap(input); } catch (CheckedException e){ throw new UncheckedException(); }}然后我可以使用.map(value -> Utils.uncheck(mapper, value))在您看來,在 Java8 流的上下文中(以及在更廣泛的 lambda 表達(dá)式上下文中)處理已檢查異常的最佳方法是什么?謝謝!
添加回答
舉報(bào)
0/150
提交
取消