The hiding of try()catch in Java (how to implement the exception block elegantly)

In the project, we will encounter exception handling. For runtime exceptions, we need to judge and handle ourselves. For the checked exception, we need to take the initiative to deal with it.
But the cumbersome try{}caht is nested in the code, and it looks very uncomfortable. Here we will not discuss the performance, as far as the code is concerned, let's see how to hide it. The principle is the same. It becomes how to write. Let's see how to handle exception blocks gracefully.

before this. You need to know the following concepts: It is an idea of ​​functional programming proposed by java8, by wrapping the code as a parameter passing behavior, that is, wrapping the code logic as a parameter and passing it to the method.
行为参数化:

Lambda表达式:
Java8 puts forward: Lambda expression is understood as a way to concisely express an anonymous function that can be passed. It has no name, but it has a function body, a parameter list, and a return type. An exception type can be thrown. The packaging code logic is the use of Lambda expressions as parameters.

函数式接口:
Essentially, it is an ordinary interface with only one abstract method, which can be implicitly converted into a Lambda expression, and it needs to be defined with annotations (@FunctionalInterface). Default methods and static methods do not need to be abstract methods and can be defined in functional interfaces.

@FunctionalInterfacepublic
interface ObjectMethodFunctionalInterface {
    
    
void count(int i);
String toString(); //same to Object.toString
int hashCode(); //same to Object.hashCode
boolean equals(Object obj); //same to Object.equals
}

If multiple abstract methods are additionally defined in the functional interface, the signatures of these abstract methods must be the same as the public methods of Object. The interface will eventually have a certain class implementation, and the ultimate parent class of the class is Object. Therefore, functional interfaces can define public methods of Object.

	Class<?> clazz = Class.forName("类名");

This code is no stranger to my friends. This is a checked exception and a ClassNotFoundException needs to be thrown.

Normal writing:

try {
    
    
            Class<?> clazzOld = Class.forName("类名");
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }

Wording after hiding:

Class<?> clazzNew =classFind( o -> Class.forName(o),"类名");

Insert picture description here

Well, let's look at the specific implementation: very simple, what we have to do is to treat it Class<?> clazz = Class.forName("类名");as a behavior, receive a String and get a Class, so we have to define a functional interface to describe this behavior.

/**
 * @Auther: Liruilong
 * @Date: 2020/7/29 15:50
 * @Description: 由函数名获取元类Class实例
 * 函数签名:   String ==> Class
 */
@FunctionalInterface
public interface ClassFindInterface {
    
    
    Class<?> classNametoClass(String className)throws ClassNotFoundException;
}

Here, because our behavior needs to throw an exception. So an exception is also thrown in the interface.

Then, we need to define a method to pass our behavior as a parameter, and at the same time, catch our exception.

public Class classFind(ClassFindInterface classFindInterface,String className){
    
    
        Class<?> clazz =null;
        try {
    
    
            clazz = classFindInterface.classNametoClass(className);
        } catch (ClassNotFoundException e) {
    
    
            logger4j.error("˙·...·˙`˙·....·…┉═∞═…┉ ═∞═┈━═┈━═┈━═┈━═┈━═☆☆☆☆、"+e.getMessage()+"☆☆☆☆☆☆☆☆☆");
            e.printStackTrace();
        }
        return clazz;
    }

Then, we can call our method classFind method,

Class<?> clazzNew =classFind( o -> Class.forName(o),"类名");

of course. In fact, this kind of thinking is not simple to catch exceptions.

Let's look at a Demo->

Converting a text file to a string:
In my opinion; to convert a text file to a string, we need to use a high-level stream to wrap the low-level stream, and then read it out by buffering. Here, we will inevitably encounter operations such as exception handling and stream closure. Below we will make these codes abnormal. Just concentrate on the logic of writing and reading.
My thinking:
I am not very familiar with java IO. If you have a good method, please leave a message and learn from each other:

FileInputStream fileInputStream = new FileInputStream(file))
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream))
BufferedReader bufferedReader = new BufferedReader(inputStreamReader))
String str = bufferedReader.readLine()

Byte stream-"character stream-"character buffer stream is about to convert byte stream to character stream and then wrap it with advanced stream.
So my idea is to avoid too many IO stream closures and exception captures in the logic, and concentrate on processing the read logic, combining the following two technologies:

  • try(){}[automatically close the stream, 1.7 support]
  • Lambda features to achieve [behavior parameterization, 1.8]
package com.liruilong.demotext.service.utils.interfaceutils;
 
import java.io.BufferedReader;
import java.io.IOException;
 
/**
 * @Description : 函数接口,描述BufferedReader ->String的转化方式
 * @Author: Liruilong
 * @Date: 2020/3/17 15:44
 */
@FunctionalInterface
public interface InputStreamPeocess {
    
    
    /**
     * @Author Liruilong
     * @Description 方法签名 BufferedReader ->String
     * @Date 15:47 2020/3/17
     * @Param [inputStream]
     * @return com.liruilong.demotext.service.utils.InputStream
     **/
 
    String peocess(BufferedReader bufferedReader) throws IOException;
}

To perform an action, any BufferReader -> String Lambda expression can be passed in as a parameter. As long as it conforms to the signature of the peocess method.

 /**
     * @return java.lang.String
     * @Author Liruilong
     * @Description 环绕处理
     * @Date 17:14 2020/3/17
     * @Param [inputStreamPeocess, file]
     **/
 
    public static String fileToBufferedReader(InputStreamPeocess inputStreamPeocess, File file) {
    
    
         string  resoult= null;
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
    
    
            try (InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream)) {
    
    
                try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
    
    
                    resoult = inputStreamPeocess.peocess(bufferedReader);
                }
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            return resoult ;
        }
    }

carried out

/**
     * @return java.lang.String
     * @Author Liruilong
     * @Description 文件转字符串
     * @Date 17:22 2020/3/17
     * @Param [file]
     **/
 
    public static String readJsonToString(File file) {
    
    
        return  fileToBufferedReader((bufferedReader) -> {
    
    
            String str = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((str = bufferedReader.readLine()) != null) {
    
    
                stringBuilder.append(str);
            }
            return stringBuilder.toString();
        }, file);
    }

Guess you like

Origin blog.csdn.net/sanhewuyang/article/details/107690540