Due to Java’s Reflection API we have been able to inspect and alter program execution at runtime. In particular, we can observe interfaces/classes/methods and fields at runtime without knowing their names at compile time.

JDK 7 introduces a new player to this dynamic/runtime inspection, the method handle (i.e. a subclass of the abstract class java.dyn.MethodHandle). Method handles gives us unrestricted capabilities for calling non-public methods, e.g. it  can be formed on a non-public method by a class that can access it. Compared to using the Reflection API, access checking is performed when the method handle is created as opposed to every time the method is called.

Suppose we have a class which needs to allow controlled access to one of its private methods. Below is the class defining this method and describing two ways (Reflection / MethodHandle) to access it...

See the rest on <a href="http://www.java7developer.com/blog/?p=191">MethodHandles</a> at the java7developer blog.


Martijn (@java7developer)

* Apologies for not posting the material here directly this time, there was much code formatting involved :)

* In the interests of transparency, this has been x-posted to Javalobby