Creating a universal Java method wrapper for pre and post processing

Basically, I'm trying to create a static method that will serve as a wrapper for any method that I pass, and will do something before and after the actual execution of the method itself. I would prefer to do this using the new Java 8 coding style. So far I have a class that has a static method, but I'm not sure what type of parameter should be such that it can accept any method with any type of parameter and then execute his. As I mentioned, I want to do some things before and after the method executes.

For example: executeAndProcess (anyMethod (anyParam));

+4
source share
1 answer

Your method can take an instance Supplierand return its result:

static <T> T executeAndProcess(Supplier<T> s) {
    preExecute();
    T result = s.get();
    postExecute();
    return result;
}

Name it as follows:

AnyClass result = executeAndProcess(() -> anyMethod(anyParam));
+6
source

Source: https://habr.com/ru/post/1675573/


All Articles