Core Java

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:

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button