About Martijn Verburg

Martijn (aka "The Diabolical Developer") is the co-founder and CTO of jClarity. He's a London Java Community leader, founder of the "Adopt a JSR" and "Adopt OpenJDK" programmes, a speaker at major conferences and the co-author of the Well-Grounded Java Developer.

A glimpse at Java 7 MethodHandle and its usage

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);

   meth.setAccessible(true);
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  } catch (NoSuchMethodException e) {
   e.printStackTrace();
  } catch (SecurityException e) {
   e.printStackTrace();
  }

  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);
   System.out.println("mh=" + mh);
  } 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) {
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   e.printStackTrace();
  }
 }

 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) {
   e.printStackTrace();
  }
 }

 public static void main(String[] args) {
  withReflectionArgs();
  withMhArgs();
 }
}



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:

run:
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;
mh=bar(MethodAccessExampleWithArgs,int,String)void
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 to java.lang.invoke. This is required to fix some defects in the API which arise from dependencies between multiple packages.

References :

Happy Coding! Do not forget to share!

Byron

Related Articles:

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


9 + = twelve



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close