Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback functions in Java

Is there a way to pass a call back function in a Java method?

The behavior I'm trying to mimic is a .Net Delegate being passed to a function.

I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.

like image 891
Omar Kooheji Avatar asked Jan 14 '09 16:01

Omar Kooheji


People also ask

Does Java have callback function?

Memory address of a function is represented as 'function pointer' in the languages like C and C++. So, the callback is achieved by passing the pointer of function1() to function2(). Callback in Java : But the concept of a callback function does not exist in Java because Java doesn't have pointer concept.

What are callback functions with an example?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

Why callback function is used?

Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.

What is callback function and how it works?

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.


2 Answers

If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well.

public class Main {      public interface Visitor{         int doJob(int a, int b);     }       public static void main(String[] args) {         Visitor adder = new Visitor(){             public int doJob(int a, int b) {                 return a + b;             }         };          Visitor multiplier = new Visitor(){             public int doJob(int a, int b) {                 return a*b;             }         };          System.out.println(adder.doJob(10, 20));         System.out.println(multiplier.doJob(10, 20));      } } 
like image 61
Gant Avatar answered Sep 24 '22 15:09

Gant


Since Java 8, there are lambda and method references:

  • Oracle Docs: Lambda Expressions
  • Oracle Docs: Method References

For example, if you want a functional interface A -> B, you can use:

import java.util.function.Function;  public MyClass {     public static String applyFunction(String name, Function<String,String> function){         return function.apply(name);     } } 

And here is how you can call it:

MyClass.applyFunction("42", str -> "the answer is: " + str); // returns "the answer is: 42" 

Also you can pass class method. For example:

@Value // lombok public class PrefixAppender {     private String prefix;      public String addPrefix(String suffix){         return prefix +":"+suffix;     } } 

Then you can do:

PrefixAppender prefixAppender= new PrefixAppender("prefix"); MyClass.applyFunction("some text", prefixAppender::addPrefix); // returns "prefix:some text" 

Note:

Here I used the functional interface Function<A,B>, but there are many others in the package java.util.function. Most notable ones are

  • Supplier: void -> A
  • Consumer: A -> void
  • BiConsumer: (A,B) -> void
  • Function: A -> B
  • BiFunction: (A,B) -> C

and many others that specialize on some of the input/output type. Then, if it doesn't provide the one you need, you can create your own FunctionalInterface:

@FunctionalInterface interface Function3<In1, In2, In3, Out> { // (In1,In2,In3) -> Out     public Out apply(In1 in1, In2 in2, In3 in3); } 

Example of use:

String computeAnswer(Function3<String, Integer, Integer, String> f){     return f.apply("6x9=", 6, 9); }  computeAnswer((question, a, b) -> question + "42"); // "6*9=42" 

And you can also do that with thrown exception:

@FunctionalInterface interface FallibleFunction<In, Out, Ex extends Exception> {     Out get(In input) throws Ex; } public <Ex extends IOException> String yo(FallibleFunction<Integer, String, Ex> f) throws Ex {     return f.get(42); } 
like image 24
Juh_ Avatar answered Sep 24 '22 15:09

Juh_