使用过 Java 的函数接口,就会被简介的语法深深的吸引,苦于代码中大量的 try...catch 繁琐代码,最近借鉴 java.util.Optional 的实现写了个简化的小工具。

Long.valueOf() 为例,假如需要把一个字符串转换为long,如果转换失败则设置默认值为 -1,一般会作如下处理:

String param = "10s";

long result;
try {
    result = Long.parseLong(param);
} catch (Exception e) {
    // 捕获异常处理

    result = -1L;
}

如果使用简化工具:

Long result = Try.of(() -> Long.valueOf(param)).trap(e -> {
    // 自行异常处理
}).get(-1L);

或者:

Long result = Try.<String, Long>of(Long::valueOf).trap(Throwable::printStackTrace).apply(param).get(-1L);

如果不需要异常处理:

Long result = Try.of(() -> Long.valueOf(param)).get(-1L);
// Long result = Try.<String, Long>of(Long::valueOf).apply(param).get(-1L);

如果处理没有返回值的代码,如下:

ArrayList<String> list = new ArrayList<>();

Try.<String>of(v -> list.add(10, v))
        .trap(e -> System.out.println(e.getMessage()))
        .accept("test");

其它情况的简单使用示例:

public static void main(String[] args) {
    // 有返回值,无入参
    String param = "s";
    Long result = Try.of(() -> Long.valueOf(param)).get(0L);
    System.out.println("Long.valueOf 1: " + result);

    result = Try.of(() -> Long.valueOf(param)).get();
    System.out.println("Long.valueOf 2: " + result);

    // 有返回值,有入参
    result = Try.<String, Long>of(s -> Long.valueOf(s))
            .apply(param)
            .trap((e) -> System.out.println("Long.valueOf exception: " + e.getMessage()))
            .andFinally(() -> System.out.println("Long.valueOf finally run code."))
            .finallyTrap((e) -> System.out.println("Long.valueOf finally exception: " + e.getMessage()))
            .get();
    System.out.println("Long.valueOf 3: " + result);

    ArrayList<String> list = null;

    // 无返回值,无入参
    Try.of(() -> Thread.sleep(-1L))
            .andFinally(() -> list.clear())
            // .andFinally(list::clear) //https://stackoverflow.com/questions/37413106/java-lang-nullpointerexception-is-thrown-using-a-method-reference-but-not-a-lamb
            .run();

    // 无返回值,有入参
    Try.<String>of(v -> list.add(0, v)).accept("test");
}

小工具的实现链接

— The End —
Last modification:December 22nd, 2020 at 04:19 pm
If you think my article is useful to you, please feel free to appreciate