Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));

like image 738
Jesus Avatar asked Apr 24 '17 23:04

Jesus


People also ask

What is t in generics Java?

< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.


1 Answers

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));
like image 161
shmosel Avatar answered Oct 05 '22 23:10

shmosel