DEV Community

MiniSoda
MiniSoda

Posted on

5

How to write a callback function in Java

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

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (2)

Collapse
 
mategreen profile image
matej

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();
}
Collapse
 
kdfemi profile image
MiniSoda

Whoa! Never knew this existed. Will try implementing this

PulumiUP 2025 image

From Infra to Platforms: PulumiUP 2025 Panel

Don’t miss the expert panel at PulumiUP 2025 on May 6. Learn how teams are evolving from infrastructure engineering to platform engineering—faster, more secure, and at scale.

Save Your Spot

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay