为前后处理创建通用Java方法包装器

Jes*_*sus 5 java java-8 functional-interface

我基本上试图创建一个静态方法,它将作为我传递的任何方法的包装器,并将在方法本身的实际执行之前和之后执行某些操作.我更喜欢使用Java 8新的编码风格.到目前为止,我有一个具有静态方法的类,但我不确定参数类型应该是什么,因此它可以采用任何类型的参数的任何方法,然后执行它.就像我提到的,我希望在方法执行之前和之后做一些事情.

例如:executeAndProcess(anyMethod(anyParam));

shm*_*sel 8

您的方法可以接受Supplier实例并返回其结果:

static <T> T executeAndProcess(Supplier<T> s) {
    preExecute();
    T result = s.get();
    postExecute();
    return result;
}
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

AnyClass result = executeAndProcess(() -> anyMethod(anyParam));
Run Code Online (Sandbox Code Playgroud)

  • @markspace你必须返回null:`executeAndProcess(() - > {voidMethod(); return null;});`.或者您可以创建另一个接受"Runnable"的变体.从OP的[评论](http://stackoverflow.com/questions/43599406/create-generic-java-method-wrapper-for-pre-and-post-processing/43599608#comment74249386_43599406)我认为他期待的方法与返回类型. (2认同)
  • 像`static void executeAndProcess(Runnable r){preExecute(); r.run(); postExecute(); }`.您可能想要使用不同的方法名称; lambdas有时会导致过载模糊. (2认同)