How to write a callback function in Java
MiniSoda

MiniSoda @kdfemi

About: I love Angular I know Java because i have to

Location:
Nigeria
Joined:
Oct 13, 2019

How to write a callback function in Java

Publish Date: Jan 27 '20
7 2

This is my first article on dev.to and programming in general. I recently developed an app for my company after completion, i was trying to clean up my code and do some refactoring, when i hit a block where i have two similar codes the only difference was calling a different method, me being a bit of newbie in Java but familiar with JavaScript was puzzled on how i can refactor this line into a method pass a method reference as a method parameter, it was a little bit tricky to get but i was able to get it to work using interface. a little snippet can be found below on how i implemented this.

public class MyClass {
    public static void main(String args[]) {
      myMethod(new GenericMethod(){
          public String call() {
              return "One";
            }
      });
       myMethod(new GenericMethod(){
        public String call() {
          return "Two";
        }
        });

        myMethod(() -> {
                return "Three";
        });
    }

    public static void myMethod(GenericMethod g) {
        System.out.println("This method called " + g.call());
    }  
    public interface GenericMethod {
        public String call();
    }
}

I created an interface GenericMethod with just one method call() then created a method myMethod with GenericMethod as a method parameter, I called GenericMethod.call() inside my method. to call the myMethod I simply pass a new instance of GenericMethod and override the call() method. You can make the code cleaner by using arrow notation instead of the new keyword as seen in the code above. The code above output the following to the console

This method called One
This method called Two
This method called Three

Comments 2 total

  • matej
    matejJan 30, 2020

    Hi, you can also use java interface Supplier for the same purpose. Something like this:

    Supplier<String> supplier = () -> "one";
    System.out.println(supplier.get());
    

    or in method

    System.out.println(myMeth(() -> "one"));
    ...
    String myMeth(Supplier<String> s) {
       return s.get();
    }
    
    • MiniSoda
      MiniSodaJan 31, 2020

      Whoa! Never knew this existed. Will try implementing this

Add comment