What is a substitute for a function pointer in Java?

Asked 1 years ago, Updated 1 years ago, 95 views

There are about 10 lines of methods. I want to create a few more methods that do almost the same thing, ignoring differences like changing a few lines of code. Function pointers replace that with almost one line, but Java doesn't have function pointers.

What's the substitute for a function pointer?

java closures function-pointers

2022-09-21 21:29

1 Answers

There is an Anonymous inner class that can replace function pointers.

If there is a function that receives String as a parameter and returns int, First, define an interface that has only the method.

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

As shown above, the method is accessible from an instance of StringFunction.

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

This is how you call it.

Also, if you use the lambda expression in java 8, you can use ref.taking Method (parameter ->processing); like this.


2022-09-21 21:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.