Over a million developers have joined DZone.

A Glimpse at MethodHandle and its Usage

DZone's Guide to

A Glimpse at MethodHandle and its Usage

· Java Zone
Free Resource

Are you joining the containers revolution? Start leveraging container management using Platform9's ultimate guide to Kubernetes deployment.

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.


public class MethodAccessExampleWithArgs {
private final int i;

public MethodAccessExampleWithArgs(int i_) {
i = i_;

private void bar(int j, String msg) {
System.out.println("Private Method \'bar\' successfully accessed : "
+ i +", "+ j +" : "+ msg +"!");

// Using Reflection
public static Method makeMethod() {
Method meth = null;

try {
Class<?>[] argTypes =
new Class[] { int.class, String.class };

meth = MethodAccessExampleWithArgs.class.
getDeclaredMethod("bar", argTypes);

} catch (IllegalArgumentException e) {
} catch (NoSuchMethodException e) {
} catch (SecurityException e) {

return meth;

// Using method handles
public static MethodHandle makeMh() {
MethodHandle mh;

MethodType desc = MethodType.methodType(void.class, int.class, String.class);

try {
mh = MethodHandles.lookup().findVirtual(MethodAccessExampleWithArgs.class, "bar", desc);
} catch (NoAccessException e) {
throw (AssertionError)new AssertionError().initCause(e);
return mh;

Following, is a class meant to test the two approaches of accessing the private method “bar” :

public class MethodAccessMain {
    private static void withReflectionArgs() {
        Method meth = MethodAccessExampleWithArgs.makeMethod();
        MethodAccessExampleWithArgs mh0 =
            new MethodAccessExampleWithArgs(0);
        MethodAccessExampleWithArgs mh1 =
            new MethodAccessExampleWithArgs(1);
        try {
            System.out.println("Invocation using Reflection");
            meth.invoke(mh0, 5, "Jabba the Hutt");
            meth.invoke(mh1, 7, "Boba Fett");
        } catch (IllegalAccessException e) {
        } catch (IllegalArgumentException e) {
        } catch (InvocationTargetException e) {
    private static void withMhArgs() {
        MethodHandle mh = MethodAccessExampleWithArgs.makeMh();
        MethodAccessExampleWithArgs mh0 =
            new MethodAccessExampleWithArgs(0);
        MethodAccessExampleWithArgs mh1 =
            new MethodAccessExampleWithArgs(1);
        try {
            System.out.println("Invocation using Method Handle");
            mh.invokeExact(mh0, 42, "R2D2");
            mh.invokeExact(mh1, 43, "C3PO");
        } catch (Throwable e) {
    public static void main(String[] args) {

How to run the code – JDK7 b129 and Netbeans 7.0 Beta 2

The above code has been tested with build 129 of JDK 7, under Netbeans IDE 7.0 Beta 2 and for it to work, it required the following extra VMOptions: -XX:+UnlockExperimentalVMOptions -XX:+EnableMethodHandles -XX:+EnableInvokeDynamic under Run >> Set Project Configuration >> Customize >> VMoptions in order to make use of InvokeDynamic and MethodHandle without receiving a runtime exception.

Issues with JDK7 b131 and Netbeans 7.0 Beta 2

If you’ve upgraded to the latest build – 131 – the outcome starts to be dependent of the circumstances under which you compile and run your code. More specifically, the Netbeans IDE 7.0 Beta 2 outputs the following:


Invocation using Reflection
Private Method 'bar' successfully accessed : 0, 5 : Jabba the Hutt!
Private Method 'bar' successfully accessed : 1, 7 : Boba Fett!

java.dyn.WrongMethodTypeException: (ILjava/lang/String;)V cannot be called as ([Ljava/lang/Object;)Ljava/lang/Object;
Invocation using Method Handle
at ben.example.MethodAccessMain.withMhArgs(MethodAccessMain.java:46)
at ben.example.MethodAccessMain.main(MethodAccessMain.java:55)

BUILD SUCCESSFUL (total time: 0 seconds)

Issues with JDK7 b131 and Eclipse 3.6.2

The example has been further tested on Eclipse 3.6.2 Helios with the same parameters -XX:+UnlockExperimentalVMOptions -XX:+EnableMethodHandles -XX:+EnableInvokeDynamic mentioned under Run>>Run Configurations>>Arguments>>VM arguments, but we have been provided with an identical output.

From the exception we have been prompted with, we can see that our method which was expected to be called with an int (I), a string (Ljava/lang/String) and return a void (V), is instead called with an array of Object, and returns an Object. This shows that there are some issues with the compiler used from within the IDE (which may be different from the command-line compiler).

Running the code JDK7 b131 on the command line

If you happen to have a post-129 JDK7 build on your computer and want to run the afore-mentioned examples without any problems, you should probably stick to compiling (javac) and running ( java -XX:+UnlockExperimentalVMOptions -XX:+EnableMethodHandles -XX:+EnableInvokeDynamic com.wgjd.MethodHandleExample.MethodAccessMain) your MethodHandle code from the command line.

Fix for JDK7 b131 and IDEs

Currently there is no set date of when we will be able to run method handles without the extra VMOptions overhead, but should you want to keep up with the latest developments of the Da Vinci Machine Project which concerns itself with the implementation of dynamic invocation, make sure you subscribe to its mailing list.

It is also worth mentioning that from the previously mentioned mailing list, we find out that there is a complex change which consolidates the multi-package code into a single package and consists of preparing for a clean rename from java.dyn tojava.lang.invoke. This is required to fix some defects in the API which arise from dependencies between multiple packages.

MethodHandles are covered in full in our The Well-Grounded Java Developer title

From http://www.java7developer.com/blog/?p=191

Moving towards a private or Hybrid cloud infrastructure model? Get started with our OpenStack Deployment Models guide to learn the proper deployment model for your organization.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}