Java Methods as JSFunctions

July 27, 2016 | 2 min Read

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:

var server = http.createServer(function(request, response) {
  // implement the callback
});

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

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

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.

Ian Bull

Ian Bull

Ian is an Eclipse committer and EclipseSource Distinguished Engineer with a passion for developer productivity.

He leads the J2V8 project and has served on several …