Tuesday, May 29, 2012

CallBack example in java?


Create a class Callback.java

package com.etretatlogiciels.callback.example;

public interface Callback
{
 void methodToCall();
}

Create another class CallbackImpl.java

package com.etretatlogiciels.callback.example;

public class CallbackImpl implements Callback
{
 @Override
 public void methodToCall()
 {
  System.out.println( "I've been called back!" );
 }
}
Create another class Caller.java

package com.etretatlogiciels.callback.example;

/**
 * This is my idea of how a formal call-back mechanism works. There are examples in the
 * real world, very common in Android code, for instance: look for View.OnClickListener().
 */
public class Caller
{
 public Callback callback = null;

/* register a method to be called back at some future, arbitrary point */
 public void register( Callback callback )
 {
  this.callback = callback;
 }

/* how Caller invokes the call-back method at the appropriate juncture  */
 public void execute()
 {
  this.callback.methodToCall();
 }

/* directly execute a method (I don't see this is a "call-back" at all) */
 public void execute( Callback callback )
 {
  callback.methodToCall();
 }

 public static void main( String args[] )
 {
  Caller  caller   = new Caller();
  Callback callback = new CallbackImpl();

  /* Demonstrate simple calling back.
   */
  caller.register( callback );
  caller.execute();

/*Demonstrate direct calling back (here, immediate execution) by creating an "on
*the fly" call-back. In a real world example, caller.execute( Callback callback )* would be a mechanism that properly establishes a situation in which, later, the* "direct" call would issue. This is very common in Android code as noted above.
*/
  caller.execute( new Callback()
   {
    public void methodToCall()
    {
   System.println( "This is our \"on the fly\" method..." );
    }
   }
  );
 }
}

Below is the output
I've been called back!
This is our "on the fly" method...

No comments:

Post a Comment