Search code examples
javajava-8functional-interface

Create generic Java method wrapper for pre and post processing


I'm basically trying to create a static method that will serve as a wrapper for any method I pass and will execute something before and after the actual execution of the method itself. I'd prefer to do it using Java 8 new coding style. So far I have a class that has a static method, but I'm not sure what the parameter type should be so it can take any method with any type of parameter and then execute it. Like i mentioned I want to do some stuff before and after the method executes.

For example: executeAndProcess(anyMethod(anyParam));


Solution

  • Your method can accept a Supplier instance and return its result:

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

    Call it like this:

    AnyClass result = executeAndProcess(() -> anyMethod(anyParam));