java在stream中异常处理问题

Java Lamdba Api缺陷

  • 问题:Java在Stream中只能使用TryCatch处理check异常,无法throw处理
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
	//在lambda中处理ClassNotFoundException只能进行tryCatch处理,无法抛出给上层处理
	public List<Class> getClazz(List<String> names) {
        return names.stream()
                .map(className -> {
                            try {
                                return Class.forName(className);
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                                return getClass();
                            }
                        }
                )
                .collect(Collectors.toList());
    }
  • 解决:定义Fun接口与lambda包装方法,利用泛型throw出原始异常
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 @FunctionalInterface
    interface ExceptionFunction<T, R, E extends Exception> {
        R apply(T t) throws E;
    }

    /**
     * 包装异常
     */
    public static <T, R, E extends Exception> Function<T, R> wrap(ExceptionFunction<T, R, E> f) throws E {
        return t -> {
            try {
                return f.apply(t);
            } catch (Exception e) {
                throwUnCheckException(e);
                return null;
            }
        };
    }

    /**
     * 利用泛型擦除机制将unCheck——>Exception
     */
    public static <E extends Exception> void throwUnCheckException(Exception e) throws E {
        throw (E) e;
    }
1
2
3
4
5
6
//完美throws原始check异常
    public static List<Class> findClasses(List<String> names) throws ClassNotFoundException {
        return names.stream()
                .map(LambdaCheckedUtils.wrap(Class::forName))
                .collect(Collectors.toList());
    }