Java 8 Lambda function that throws exception?

后端 未结 26 1766
臣服心动
臣服心动 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条回答
  •  一生所求
    2020-11-22 03:19

    You could however create your own FunctionalInterface that throws as below..

    @FunctionalInterface
    public interface UseInstance {
      void accept(T instance) throws X;
    }
    

    then implement it using Lambdas or references as shown below.

    import java.io.FileWriter;
    import java.io.IOException;
    
    //lambda expressions and the execute around method (EAM) pattern to
    //manage resources
    
    public class FileWriterEAM  {
      private final FileWriter writer;
    
      private FileWriterEAM(final String fileName) throws IOException {
        writer = new FileWriter(fileName);
      }
      private void close() throws IOException {
        System.out.println("close called automatically...");
        writer.close();
      }
      public void writeStuff(final String message) throws IOException {
        writer.write(message);
      }
      //...
    
      public static void use(final String fileName, final UseInstance block) throws IOException {
    
        final FileWriterEAM writerEAM = new FileWriterEAM(fileName);    
        try {
          block.accept(writerEAM);
        } finally {
          writerEAM.close();
        }
      }
    
      public static void main(final String[] args) throws IOException {
    
        FileWriterEAM.use("eam.txt", writerEAM -> writerEAM.writeStuff("sweet"));
    
        FileWriterEAM.use("eam2.txt", writerEAM -> {
            writerEAM.writeStuff("how");
            writerEAM.writeStuff("sweet");      
          });
    
        FileWriterEAM.use("eam3.txt", FileWriterEAM::writeIt);     
    
      }
    
    
     void writeIt() throws IOException{
         this.writeStuff("How ");
         this.writeStuff("sweet ");
         this.writeStuff("it is");
    
     }
    
    }
    

提交回复
热议问题