Skip to content

Instantly share code, notes, and snippets.

@pvrego
Created March 5, 2019 20:56
Show Gist options
  • Save pvrego/cb4e8b541475c07ad12d98d85337e383 to your computer and use it in GitHub Desktop.
Save pvrego/cb4e8b541475c07ad12d98d85337e383 to your computer and use it in GitHub Desktop.
Callbacks in Java
// From https://www.quora.com/What-are-callback-methods-in-Java
// Java program to illustrate synchronous callback
interface OnGeekEventListener {
// this can be any type of method
void onGeekEvent();
}
class B {
private OnGeekEventListener mListener; // listener field
// setting the listener
public void registerOnGeekEventListener(OnGeekEventListener mListener){
this.mListener = mListener;
}
// my synchronous task
public void doGeekStuff(){
// perform any operation
System.out.println("Performing callback before synchronous Task");
// check if listener is registered.
if (this.mListener != null) {
// invoke the callback method of class A
mListener.onGeekEvent();
}
}
// Driver Function
public static void main(String[] args){
B obj = new B();
OnGeekEventListener mListener = new A();
obj.registerOnGeekEventListener(mListener);
obj.doGeekStuff();
}
}
class A implements OnGeekEventListener {
@Override
public void onGeekEvent(){
System.out.println("Performing callback after synchronous Task");
// perform some routine operation
}
// some class A methods
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment