5

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

Jesus
  • 318
  • 1
  • 4
  • 17
  • Why a static method? I don't see how a static method is a "wrapper." – markspace Apr 25 '17 at 00:13
  • A static method so I can import it to different class and just call it. For example: executeAndProcess(anyMethod(anyParam)); – Jesus Apr 25 '17 at 00:17
  • Does it need to return anything? – shmosel Apr 25 '17 at 00:19
  • How do you intend to bind those parameters? – markspace Apr 25 '17 at 00:19
  • Yeah I want it to return whatever the method was supposed to return. Not sure what do you mean by bind. I just want to be able to execute the method inside my method when I want to, with the parameters I passed and return what it was meant to return. – Jesus Apr 25 '17 at 00:21
  • Try some code with different message signatures, show us what you're trying to do. – markspace Apr 25 '17 at 00:23
  • This is the kind of thing where [tag:aop] would be useful, as it would avoid changes at the call site. This would make sure that no caller forgets to wrap calls in `executeAndProcess()`. – Didier L Apr 25 '17 at 09:13

1 Answers1

9

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));
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • 2
    @markspace You would have to return null: `executeAndProcess(() -> { voidMethod(); return null; });`. Or you could make another variation that accepts a `Runnable`. From OP's [comment](http://stackoverflow.com/questions/43599406/create-generic-java-method-wrapper-for-pre-and-post-processing/43599608#comment74249386_43599406) I took it that he's expecting methods with return types. – shmosel Apr 25 '17 at 00:25
  • Thank you shmosel. There could be a case where one of the methods could have void return. How would that variation look like? – Jesus Apr 25 '17 at 00:30
  • 2
    Something like `static void executeAndProcess(Runnable r) { preExecute(); r.run(); postExecute(); }`. You might want to use a different method name; lambdas can sometimes cause overload ambiguity. – shmosel Apr 25 '17 at 00:32
  • Any ideas how to get this working with checked exceptions? – Jesus Apr 25 '17 at 01:08
  • 1
    Either pass a full try/catch block, or use an interface that throws exceptions, like `Callable`. – shmosel Apr 25 '17 at 01:12