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:

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.

 

2 Responses to “Java Methods as JSFunctions”

  1. Mike Cargal says:

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

  2. Ian Bull says:

    Mike,

    I completely agree with you. I was just trying to see how a DSL using unicode characters ‘felt’. Similar to how something like underscore (_) or JQuery ($) use a single symbol (albeit a typeable one). After messing with it, I came to same conclusion that you did that it’s a terrible idea. I meant to remove that before I published the blog. Thanks for pointing this out, and thanks for the discussion.

Leave a Reply

2 responses so far

Written by . Published in Categories: EclipseSource News

Looking for a job?

X
Karlsruhe / Remote
JavaScript
Mobile
Karlsruhe / Victoria / Remote
Windows
Mobile
Karlsruhe / Victoria / Remote
Java
Android
Mobile