Possible Duplicate:
What's the nearest substitute for a function pointer in Java?
I just have a situation where it would be nice to have the functionality of something similar to function pointers like you might use in c or c++. The best thing I can think of is combining Runnables and launch them in a different thread. Suggestions?
Until they add closures to java, the thing seems closest to java.lang.reflect.Method. For example Method method = SomeClass.getMethod("methodName", methodParameterTypes)
Then you can pass the method around (like a function pointer) and call invoke(..) on it, passing an object (or null if static)
But this is not quite a good practice. You can define an interface, or use an existing one Runnable / Callable, implement it inline, and pass the instance.
Use Functors, aka Function Objects.
Java has no first-class functions, so function objects are usually expressed by an interface with a single method (most commonly the Callable interface), typically with the implementation being an anonymous inner class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With