Java's Substitute for Function Pointers
Java's lack of function pointers can hinder the creation of modular, reusable code. However, there's a solution: anonymous inner classes.
Consider a requirement for multiple methods performing identical operations except for a single line of calculation. Ideally, passing a function pointer would suffice, but Java doesn't support that. The alternative is to define an interface with the desired function as its sole member.
For instance, to define a function that takes a string and returns an integer:
interface StringFunction { int func(String param); }
Now, a method that accepts a function pointer can intake a StringFunction instance:
public void takingMethod(StringFunction sf) { int i = sf.func("my string"); // do other operations ... }
Calling this method would look like this:
ref.takingMethod(new StringFunction() { public int func(String param) { // Implementation for the single changed line } });
In Java 8, this can be further simplified using lambda expressions:
ref.takingMethod(param -> { // Implementation for the single changed line });
By utilizing anonymous inner classes or lambda expressions, Java programmers can achieve the functionality of function pointers, offering flexibility and code reusability.
The above is the detailed content of How Can Java Mimic Function Pointers for Modular Code?. For more information, please follow other related articles on the PHP Chinese website!