-1

I have an alert message and I need to call this from different part of my code. Base on user interaction I will show this alert and pass some parameter based on this parameter my alert should behave for eg.

private void alert(String message, String title, Method methodReference) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(message);
        builder.setTitle(title);
        builder.setCancelable(false);
        builder.setPositiveButton("Yes", (DialogInterface.OnClickListener) (dialog, which) -> {
           methodReference();    // I want to replace methodReference with that method that will pass while calling alert
        });

        builder.setNegativeButton("No", (DialogInterface.OnClickListener) (dialog, which) -> {
            dialog.cancel();
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

I want to replace methodReference with that method that will pass while calling alert

eg. alert("message", "title", doWork()); or

alert("message", "title", workInProgress());

  • Does this answer your question? [How to pass a function as a parameter in Java?](https://stackoverflow.com/questions/4685563/how-to-pass-a-function-as-a-parameter-in-java) – experiment unit 1998X Feb 07 '23 at 06:25
  • Though, what you want to do - passing `doWork(), workInProgress() etc etc` sounds like you want the strategy pattern https://stackoverflow.com/a/10137808/16034206 – experiment unit 1998X Feb 07 '23 at 06:27

1 Answers1

0

Not a method directly, but you could make use of a FunctionalInterface, or a callback:

Info: A functional interface is an interface with just one method declaration and nothing more -> Thus aiming to be "used as a lambda".

Custom implementation

Create a functional interface

@FunctionalInterface // Annotation not really needed
public interface Callback {
    void handle(String str);
}

Create a method which uses this Interface as a parameter

public void message(String msg, String title, Callback callback) {
    callback.handle(msg);
}

Use the method as follows

// "Normal lambda" - Prints msg: ("Hello")
message("Hello", "World", str -> {
    System.out.println(str);
});

// Method reference, for shorter syntax: Does the same thing
message("Hello", "World", System.out::println);

Existing implementation

Instead of creating a custom Callback, you can just use any of the functional interfaces Java provides out of the box:

E.g. Function, BiFunction, Consumer, ...

For further explanation on how to use a Functional interface, I highly recommend this article by Baeldung. :)

Hope this helped!

Z-100
  • 518
  • 3
  • 19