Java 8 Lambda function that throws exception?

后端 未结 26 2040
臣服心动
臣服心动 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条回答
  •  Happy的楠姐
    2020-11-22 03:28

    I use an overloaded utility function called unchecked() which handles multiple use-cases.


    SOME EAMPLE USAGES

    unchecked(() -> new File("hello.txt").createNewFile());
    
    boolean fileWasCreated = unchecked(() -> new File("hello.txt").createNewFile());
    
    myFiles.forEach(unchecked(file -> new File(file.path).createNewFile()));
    

    SUPPORTING UTILITIES

    public class UncheckedUtils {
    
        @FunctionalInterface
        public interface ThrowingConsumer {
            void accept(T t) throws Exception;
        }
    
        @FunctionalInterface
        public interface ThrowingSupplier {
            T get() throws Exception;
        }
    
        @FunctionalInterface
        public interface ThrowingRunnable {
            void run() throws Exception;
        }
    
        public static  Consumer unchecked(
                ThrowingConsumer throwingConsumer
        ) {
            return i -> {
                try {
                    throwingConsumer.accept(i);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            };
        }
    
        public static  T unchecked(
                ThrowingSupplier throwingSupplier
        ) {
            try {
                return throwingSupplier.get();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    
        public static void unchecked(
                ThrowingRunnable throwing
        ) {
            try {
                throwing.run();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    

提交回复
热议问题