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
Top comments (2)
Hi, you can also use java interface Supplier for the same purpose. Something like this:
or in method
Whoa! Never knew this existed. Will try implementing this