Home >Java >javaTutorial >How Can I Pass Functions as Parameters in Java?

How Can I Pass Functions as Parameters in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-12-16 03:58:10643browse

How Can I Pass Functions as Parameters in Java?

Function as parameter in Java

In Java, how to pass a function as parameter to another function?

Java 8 and above

Use Java 8 lambda expression, when you have a class or interface (sometimes called a SAM type) with only one abstract method, for example:

public interface MyInterface {
    String doSomething(int param1, String param2);
}

then you can use a lambda expression instead where MyInterface is used:

class MyClass {
    public MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
}

For example, you can To execute quickly by creating a new thread:

new Thread(() -> someMethod()).start();

and use method reference syntax to make it more concise:

new Thread(this::someMethod).start();

If does not use lambda expression formula, the last two examples will look like this:

new Thread(new Runnable() { someMethod(); }).start();

Java Pre-8 versions

A common pattern is to "wrap" a function inside an interface, such as Callable, and then pass a Callable:

public T myMethod(Callable<T> func) {
    return func.call();
}

This pattern is called the command pattern .

Remember that it is best to create interfaces for specific purposes. If you choose to use call, replace T above with any type of return value you expect, such as String.

The above is the detailed content of How Can I Pass Functions as Parameters in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn