Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 pass method as parameter

Currently getting into Java 8 lambda expressions and method references.

I want to pass a method with no args and no return value as argument to another method. This is how I am doing it:

public void one() {     System.out.println("one()"); }  public void pass() {     run(this::one); }  public void run(final Function function) {     function.call(); }  @FunctionalInterface interface Function {     void call(); } 

I know there is a set of predefined functional interfaces in java.util.function such as Function<T,R> but I didn't find one with no arguments and not producing a result.

like image 884
Torsten Römer Avatar asked Aug 07 '14 15:08

Torsten Römer


People also ask

Can we pass method as a parameter in Java?

There's no concept of a passing method as a parameter in Java from scratch. However, we can achieve this by using the lambda function and method reference in Java 8.

Can you pass a method into a method in Java?

We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() .

Can we pass an object as parameter to call a method in Java?

In Java, we can pass a reference to an object (also called a "handle")as a parameter.


1 Answers

It really does not matter; Runnable will do too.

Consumer<Void>, Supplier<Void>, Function<Void, Void> 
like image 58
Joop Eggen Avatar answered Oct 18 '22 09:10

Joop Eggen