Created
August 14, 2015 22:48
-
-
Save willeccles/fa01b73f12121a03ebc3 to your computer and use it in GitHub Desktop.
This is how to pass a method to another method in Java 8+.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// while this is not technically a method, a Runnable is close enough for me. | |
// this method wants a "method" as an input | |
void canHazMethod(Runnable methodToRun) { | |
// run the method passed in | |
methodToRun.run(); | |
} | |
// this is the method I will use: | |
Runnable myMethod = () -> { | |
System.out.println("my method has been run"); | |
}; | |
// you can see how nice this is compared to Java 7 and earlier: | |
Runnable anotherMethod = new Runnable() { | |
public void run() { | |
System.out.println("this is another method to be run"); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update: better method of doing this here.