Java 8 Lambda function that throws exception?

后端 未结 26 2155
臣服心动
臣服心动 2020-11-22 03:14

I know how to create a reference to a method that has a String parameter and returns an int, it\'s:

Function         


        
26条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 03:30

    You can.

    Extending @marcg 's UtilException and adding generic where necessary: this way, the compiler will force you again to add throw clauses and everything's as if you could throw checked exceptions natively on java 8's streams.

    public final class LambdaExceptionUtil {
    
        @FunctionalInterface
        public interface Function_WithExceptions {
            R apply(T t) throws E;
        }
    
        /**
         * .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName))
         */
        public static  Function rethrowFunction(Function_WithExceptions function) throws E  {
            return t -> {
                try {
                    return function.apply(t);
                } catch (Exception exception) {
                    throwActualException(exception);
                    return null;
                }
            };
        }
    
        @SuppressWarnings("unchecked")
        private static  void throwActualException(Exception exception) throws E {
            throw (E) exception;
        }
    
    }
    
    public class LambdaExceptionUtilTest {
    
        @Test
        public void testFunction() throws MyTestException {
            List sizes = Stream.of("ciao", "hello").map(rethrowFunction(s -> transform(s))).collect(toList());
            assertEquals(2, sizes.size());
            assertEquals(4, sizes.get(0).intValue());
            assertEquals(5, sizes.get(1).intValue());
        }
    
        private Integer transform(String value) throws MyTestException {
            if(value==null) {
                throw new MyTestException();
            }
            return value.length();
        }
    
        private static class MyTestException extends Exception { }
    }
    

提交回复
热议问题