Using Callbacks with Java

Using Callbacks with Java

Using callbacks in Java

Certainly, you know use callbacks in JavaScript, right. Or maybe pass one pointer to a function in C, for example. Ok, but, since Java 8 and method references and lambdas we can callbacks in Java. For example:

public class MyClass {

    String callback(String name, Function<String, String> myFunction) {
        return myFunction.apply(name);
    }

    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        String result = myClass.callback("Your Name", item -> "Your name is : "+item);
        System.out.println(result);
    }

}

First thing to note is I’m using function. The make part of java.util.function package. The method callback(very creative name) receive two arguments: one string to apply and one function.

And finally I invoke this in method main passing with argument one lambda, function.

So, you can use callbacks in Java.

and that’s all folks!

If you have any doubts, problems or suggestions, just leave a message.