Java Methods as JSFunctions

Java Methods as JSFunctions

When J2V8 was first released, all callbacks from JavaScript to Java required a registered Java method. That is, all Java methods that you wished to invoke had to be first registered with J2V8. For some applications this was fine, but it made for a complex programming model. Furthermore you could not use anonymous inner classes or Java 8 lambdas. With J2V8 4, this has changed.

J2V8 now allows you to create V8Functions in Java with bodies defined as anonymous inner classes or even lambda expressions. For example, say you had an http server in JavaScript which takes a callback as a parameter:

<pre lang="javascript">
var server = http.createServer(function(request, response) {
  // implement the callback
});
</pre>

With J2V8 4 you can now call createServer from Java and pass a Java method as the callback parameter.

<pre lang="java">
JSObject server = http.execute("createServer", f((V8Object receiver, V8Array parameters) -> {
  JSObject response = jsObject((V8Object) parameters.get(1));
  response.execute("writeHead", 200, o("Content-Type", "text/plain"));
  response.execute("end", "Hello, from the JavaWorld!");
  response.release();
  return null;
}));

public static V8Function f(JavaCallback callback) {
  return new V8Function(v8, callback);
}
</pre>

V8Functions are Java representations of JavaScript functions and can be used wherever a V8Object can be used. However, instead of having a body defined in JavaScript, the body is defined by implementing JavaCallback.

The complete code example for this simple Node.js HTTP Server is available on GitHub.

For more news on J2V8, follow me on Twitter.

 

2 Comments
  • Mike Cargal
    Posted at 1:29 am, July 28, 2016

    OK, I’ll bite… Why (other than “just because I can”), would you name a class ∆?

    Am I missing something? I’ve have to have a heart to heart with any developer that started naming things that required knowing special keystrokes just to type the code?

    I don’t even see what would qualify this class a being any sort of “delta”

    (OK, weird thing to get hung up on, and not the point of your post, but still…)