I have a method that’s about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that’s going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn’t have function pointers. What’s my best alternative?
Share
Anonymous inner class
Say you want to have a function passed in with a
Stringparam that returns anint.First you have to define an interface with the function as its only member, if you can’t reuse an existing one.
A method that takes the pointer would just accept
StringFunctioninstance like so:And would be called like so:
EDIT: In Java 8, you could call it with a lambda expression: