Question

Now that Java 8 was officially released here: http://www.oracle.com/technetwork/java/javase/downloads/index.html

Does anyone know if we can instantiate java-lambdas or call them from JNI? There's lots of documentation for using Lambdas and all the new features in Java but nothing for JNI :S

Was it helpful?

Solution

Lambda expressions are a compile-time Java language level artifact. The Java compiler will compile the expression into a synthetic method and generate the code necessary to create an instance of the functional interface whose single abstract method will invoke the method.

Since JNI is a runtime interface there is no such thing than a lambda expression from the JNI’s point of view. There are only JRE generated implementations of functional interfaces flying around which will execute pre-built methods. They may be created in order to implement a lambda expression, a method reference, or just created manually as the creation facility is part of the public JRE API.

“Calling a lambda” is quite simple then as “calling a lambda” means invoking the single abstract interface method of the functional interface on such a generated instance. There’s no need for any special JNI function just like there is no need for special Java language features to call that method.

What JNI could do about generating a lambda is telling the JRE to generate a functional interface implementation that will invoke a specified method. If that target method is the synthetic method generated by a Java compiler for a lambda expression, you have created a lambda via JNI then. Otherwise the generated instance will just behave like a method reference to the target method.

This answer shows how such an instance can be generated using pure Java code. Most of it consists of ordinary method calls which can be invoked by JNI as well. The only tricky part is invoking the factory method represented by the MethodHandle returned by the CallSite. Since invoke and invokeExact cannot be called by JNI you have to invoke invokeWithArguments for the final step of the creation.

To summarize the creation procedure, it is all centered about the method LambdaMetafactory.metafactory which is normally used as a bootstrap method for an invokedynamic instruction but which might be invoked like an ordinary method as well, including via JNI. It’s documentation as well as it’s class documentation is quite comprehensive.

Note that this is not even an entirely new thing. A limited predecessor already exists in Java 7.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top