Assume that I am implementing a dynamically typed language on top the JVM 7, which supports the invokedynamic instruction to link methods at runtime.
The dynamically typed language has a function add that works on integers by adding them and on strings by concatenating them. Now assume that add is called by a, say, generic list processing method that only knows (at compile-time) that it holds objects, either integers or strings or both.
How can invokedynamic help me here when compiling the the method to JVM bytecode as it has to dispatch to two different internal functions, namely the actual function that adds integers and the actual function that concatenates strings?
In short,
invokedynamiclets you invoke a method with a given signature without knowledge of the class the method belongs to. If youradd()method just takes anObject(or other common base type) as an argument, then you can haveadd(Object)methods in many otherwise unrelated classes, andinvokedynamicwill be able to invoke them. As long as the target object has the method, it will be called.