Java Pass Method as Parameter
To pass a method as a parameter in Java, you can use a functional interface and a lambda expression.
A functional interface is an interface that has a single abstract method. In Java, functional interfaces are usually annotated with the @FunctionalInterface
annotation. For example:
@FunctionalInterface
public interface MyFunction {
void apply();
}
To pass a method as a parameter, you can create a lambda expression that implements the abstract method of the functional interface. For example:
MyFunction f = () -> System.out.println("Hello, World!");
You can then pass the lambda expression as a parameter to a method:
public void execute(MyFunction f) {
f.apply();
}
To call the execute()
method and pass the lambda expression as a parameter, you can do the following:
execute(f);
Alternatively, you can pass the lambda expression directly as a parameter:
execute(() -> System.out.println("Hello, World!"));
I hope this helps! Let me know if you have any questions.