在运行时参数化 Runnable 对象

Parametrise a Runnable object at runtime

我有一个可运行的任务 (doSomething),我需要根据谁调用 运行() 来设置参数。

    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();
           ...
        }
    }

到目前为止,我唯一的选择是将匿名 class 转换为命名 class 并创建两个具有所需参数的对象。

有没有更优雅的方式?

我不确定这是否是您要查找的内容:

  // provide config 
  Map<String, String> config = new HashMap<>();
  config.put( "someKey", "someValue" );

  Consumer<Map<String, String>> consumer = cfg -> {
     Runnable doSth = () -> {
        if ( cfg.get( "someKey" ).equals( "someValue" ) ) {

        }
     };
     doSth.run();
  };

  // apply different configurations depending on your needs
  consumer.accept( config );

我建议您将 doSomething 更改为接受您的参数的 Consumer

public void foo(ScheduledExecutorService execService) {
    Consumer<YourParams> doSomething = (params) -> {
        /*Code that I DON’T want to duplicate*/
        /* small piece of code that I need to parametrise */
        // use params
    };

    // after someDelayInSeconds doSomething.run() will be called
    YourParams asyncParams = /* parameters for async execution */;
    execService.schedule(() -> doSomething.accept(asyncParams), someDelayInSeconds, TimeUnit.SECONDS);

    // this might or might not call doSomething.run()
    bar(doSomething);

}

private void bar(Consumer<YourParams> doSomething) {
    if (/* some conditions are met */) {doSomething.accept(otherParams);}
}

在计划执行中,您然后通过传递异步执行的默认参数将 doSomething 转换为 Runnable,而在 bar() 中,您直接传递您选择的替代参数。