Runnable with a parameter?

后端 未结 7 2509
后悔当初
后悔当初 2020-11-27 09:39

I have a need for a \"Runnable that accepts a parameter\" although I know that such runnable doesn\'t really exist.

This may point to fundamental flaw in the design

7条回答
  •  温柔的废话
    2020-11-27 10:12

    Since Java 8, the best answer is to use Consumer:

    https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html

    It's one of the functional interfaces, which means you can call it as a lambda expression:

    void doSomething(Consumer something) {
        something.accept("hello!");
    }
    
    ...
    
    doSomething( (something) -> System.out.println(something) )
    
    ...
    

提交回复
热议问题