-2

I have a lot of functions and want to use an array to call them. I know how to do it in c++ but dont know how to do it in java. Pseudocode of my intention bellow:

Array<function pointers> functionBook[100];
functionBook.add(function_0);
functionBook.add(function_1);
 .
 .
 .
functionBook.add(function_99);


void functionCaller(int i){
  functionBook[i](); // will call function_i()
}
3
  • Java doesn't have function pointers. It has @FunctionalInterface that you can use. Search about it. Commented Feb 7, 2021 at 15:03
  • Do not do this, but you could invoke functions using memory addresses through JNI. Commented Feb 7, 2021 at 15:08
  • 1
    @LppEdd With Project Panama you don't even need to write any JNI code. But Java methods are complicated, as they don't have a fixed address. Commented Feb 7, 2021 at 15:15

1 Answer 1

3

Try using lambdas and functional interfaces:

public static void main(String[] args) {

    List<Runnable> list = List.of(
            () -> System.out.println("first"),
            () -> System.out.println("second"),
            () -> System.out.println("third")
    );

    list.forEach(Runnable::run);

}

You can use any other interfaces, like Function<R, T> that can accept values, or create your own functional interface.

Sign up to request clarification or add additional context in comments.

1 Comment

My error, edited, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.