Java 方法的通用包装器
是否可以实现以下“伪代码”中的一些常见包装器:Java 方法的通用包装器,java,Java,是否可以实现以下“伪代码”中的一些常见包装器: Function calculateFunction=()->sampleService.calculate(“a”、“b”、1L); CalculationResult=wrapCall(CalculationFunction); 函数testFunction=()->anotherService.test(参数); TestResult结果=wrapCall(testFunction); 公共R wrapCall(函数){ log.debug(
Function calculateFunction=()->sampleService.calculate(“a”、“b”、1L);
CalculationResult=wrapCall(CalculationFunction);
函数testFunction=()->anotherService.test(参数);
TestResult结果=wrapCall(testFunction);
公共R wrapCall(函数){
log.debug(“…”);
试一试{
R结果=函数。应用();
log.debug(“…”);
返回结果;
}捕获(例外e){
log.error(“…”)
抛出新的RuntimeException()
}
}
更新1我添加了抛出RuntimeException的新语句
更新2代码的问题是它不会编译,因为使用t参数的函数类型错误,并且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);
@functioninterface
公共接口操作{
R作用();
}
公共R wrapCall(操作功能){
试一试{
R result=function.action();
返回结果;
}捕获(例外e){
抛出新的RuntimeException();
}
}
操作操作=()->sampleService.calculate(“a”,“b”,1L);
字符串结果=wrapCall(操作);
类似这样的内容:
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);
}
}
}
你已经这么做了。否?除了在异常情况下缺少
返回
,我看不出这个伪代码有问题。只需在函数和返回中正确使用泛型类型,就可以对-mass方法和将要调用该方法的对象始终使用反射API
。要向伪代码添加信息:public R wrapCall(函数){
其中在函数中
,R
是函数的返回类型。PS:实际上,它是函数
,但这仍然是伪代码;)编辑:精确定义所需内容。伪代码是正确的(对于Java来说不正确,但伪代码不需要精确)这是我不会编译的最新代码:`@functioninterface公共接口MyFunction{R action();}public R wrapCall(MyFunction函数){try{R result=function.action();返回结果;}catch(异常e){throw new RuntimeException();}}`您忘记了一个返回值,以防出现异常;)啊,我们开始..谢谢,这就是我要找的。我在execute方法的定义中缺少“”。
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);
}
}
}
final Integer i = new Executor().execute(
() -> Integer.parseInt("5")
);