Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java callback methods

Tags:

java

Can anybody help on how to implement callback methods using annotations in java ?

More detail -

Basically, I have a java method that returns nothing [void] but I wanted it to return the state of the object to the caller without changing the method signature using callback function. Hope that helps.

Thank you!

like image 240
jagamot Avatar asked Nov 12 '10 12:11

jagamot


People also ask

What is callback method?

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.

What are the types of callback?

There are two types of callbacks, differing in how they control data flow at runtime: blocking callbacks (also known as synchronous callbacks or just callbacks) and deferred callbacks (also known as asynchronous callbacks).

What is callback interface in Java?

Callback in C/C++ : The mechanism of calling a function from another function is called “callback”. 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().


1 Answers

Very simple.

In some class or interface somewhere you have a method that should be called: [access modifier] [return type] name([parameter list])...

for instance:

public void callback()

Then in some class you either override that method, or implement it, or something. Then in the code that does the callback you take an argument of the type of the class that has the callback method. For instance:

public interface Callback
{
   public void callback();
}



public class Callbackee implements Callback {
   public void callback()
   {
      System.out.println("Hey, you called.");`
   }

   static{
    new Callbackee().doCallback();
   }
}

public class CallBacker {
    Callback call;

    public void registerCallback(Callback call) {
       this.call=call;
    }

    //then just do the callback whenever you want.  You can also, of course, use collections to register more than one callback:

    public void doCallback() {
       call.callback();
    }
}

If you want to see examples of callback methods in the Java API, look at MouseListener, MouseMotionListener, KeyListener and so forth. Usually you can register more than one callback of course.

like image 67
Dude Dawg Homie Avatar answered Sep 20 '22 10:09

Dude Dawg Homie