Home >Java >javaTutorial >What\'s the Best Way to Simulate Function Pointers in Java?

What\'s the Best Way to Simulate Function Pointers in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 19:57:10882browse

What's the Best Way to Simulate Function Pointers in Java?

Nearest Alternative to Function Pointers in Java

Java lacks function pointers, presenting a challenge when creating methods that perform similar tasks with minor variations. To address this, a suitable alternative is using anonymous inner classes.

Anonymous Inner Class Solution

An anonymous inner class allows you to define a method without creating a separate named class. It follows the pattern of defining an interface with the required method and implementing it in an anonymous inner class.

For example, consider a method that takes a string as a parameter and returns an integer. First, define an interface:

interface StringFunction {
    int func(String param);
}

A method that accepts a pointer to this function would look like this:

public void takingMethod(StringFunction sf) {
   int i = sf.func("my string");
   // do whatever ...
}

To call this method, create an anonymous inner class implementing the interface:

ref.takingMethod(new StringFunction() {
    public int func(String param) {
        // body
    }
});

Alternatively, Java 8 introduces lambda expressions, which provide a more concise syntax for this purpose:

ref.takingMethod(param -> bodyExpression);

The above is the detailed content of What\'s the Best Way to Simulate Function Pointers 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