7

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!

1
  • I suggest you give a little more detail. I don't think you can implement methods using annotations, you probably mean something else.
    – krico
    Commented Nov 12, 2010 at 12:45

3 Answers 3

9

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.

1

Here is a nice tutorial about that:

http://slesinsky.org/brian/code/annotated_callback.html

Although I'm not sure if this is the thing you're thinking about.

1
  • yes...something on these lines. Can you help me with a full blown example
    – jagamot
    Commented Nov 12, 2010 at 14:50
0

You could wrap your Callback method in an http://download.oracle.com/javase/1.4.2/docs/api/java/awt/event/ActionListener.html class, then call ActionListener#actionPerformed(ActionEvent ev)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.