【发布时间】:2022-02-25 00:52:29
【问题描述】:
我有一个 Runnable 任务 (doSomething),我需要根据谁调用 run() 对其进行参数化。
Class SomeClass {
Public void foo(ScheduledExecutorService execService, ){
...
Runnable doSomething = () -> {
/*Code that I DON’T want to duplicate*/
...
/* small piece of code that I need to parametrise */
};
...
// after someDelayInSeconds doSomething.run() will be called
execService.schedule(doSomething, someDelayInSeconds, TimeUnit.SECONDS);
// this might or might not call doSomething.run()
bar(doSomething);
...
}
private void bar(Runnable doSomething){
...
if(/* some conditions are met */)
doSomething.run();
...
}
}
到目前为止,我唯一的选择是将匿名类转换为命名类并创建两个具有所需参数的对象。
会有更优雅的方式吗?
【问题讨论】:
-
参数从何而来?
-
参数将来自调用者,这些参数将表示调用 run() 的人员和原因。
标签: java lambda runnable functional-interface