方法的常见包装器

时间:2017-02-15 11:17:59

标签: java

是否可以实现一些常见的包装器,即"伪代码":

Function calculateFunction = () -> sampleService.calculate("a", "b", 1L);
CalculationResult result = wrapCall(calculateFunction);

Function testFunction = () -> anotherService.test(parameters);
TestResult result = wrapCall(testFunction);

public R wrapCall(Function<T,R> function) {
    log.debug("...");
    try {
        R result = function.apply();
        log.debug("...");
        return result;
    } catch (Exception e) {
        log.error("...")
        throw new RuntimeException()
    }
}

UPDATE 1 我添加了抛出RuntimeException的新语句

UPDATE 2 代码的问题在于它不会编译错误的函数类型与T参数和缺少&lt; R>在wrapCall方法定义中。这就是我要找的东西:

@FunctionalInterface
public interface Operation<R> {
    R action();
}

public <R> R wrapCall(Operation<R> function) {
    try {
        R result = function.action();
        return result;
    } catch (Exception e) {
        throw new RuntimeException();
    }
}

Operation<String> operation = () -> sampleService.calculate("a", "b", 1L);

String result = wrapCall(operation);

1 个答案:

答案 0 :(得分:1)

这样的事情:

public interface Operation<T> {
    T execute();
}

public class Executor {
    //...
    public <T> T execute(final Operation<T> operation) {
        log.debug("something");
        try {
            final T result = operation.execute();
            log.debug(result);
            return result;
        } catch (final Exception e) {
            log.error("error", e);
            throw new RuntimeException("omg", e);
        }
    }
}

然后通过使用lamdbdas的匿名实现来使用接口:

final Integer i = new Executor().execute(
    () -> Integer.parseInt("5")
);