highlight.js

Monday, August 2, 2021

Javet - Java and JavaScript Interop

Javet is Java + V8 (JAVa + V + EighT). It is an awesome way of embedding Node.js and V8 in Java.

From v0.9.8, Javet allows injecting arbitrary Java objects into V8 which enables the complete interop between Java and JavaScript. To enable this feature, application just needs to call v8Runtime.setConverter(new JavetProxyConverter());. Here are 3 examples.

Inject a Static Class

v8Runtime.getGlobalObject().set("System", System.class);
v8Runtime.getExecutor("function main() {\n" +
        // Java reference can be directly called in JavaScript.
        "  System.out.println('Hello from Java');\n" +
        // Java reference can be directly assigned to JavaScript variable.
        "  const println = System.out.println;\n" +
        // Java reference can be directly assigned to JavaScript variable.
        "  println('Hello from JavaScript');\n" +
        "}\n" +
        "main();").executeVoid();
v8Runtime.getGlobalObject().delete("System");

/*
 * Output:
 *   Hello from Java
 *   Hello from JavaScript
 */

Inject an Enum

v8Runtime.getGlobalObject().set("Color", Color.class);
System.out.println(v8Runtime.getExecutor("Color.pink.toString();").executeString());
System.out.println("The enum in JavaScript is the one in Java: " +
        (Color.pink == (Color) v8Runtime.getExecutor("Color.pink;").executeObject()));
v8Runtime.getGlobalObject().delete("Color");

/*
 * Output:
 *   java.awt.Color[r=255,g=175,b=175]
 *   The enum in JavaScript is the one in Java: true
 */

Inject a Pattern

Pattern pattern = Pattern.compile("^\\d+$");
v8Runtime.getExecutor("function main(pattern) {\n" +
        "  return [\n" +
        "    pattern.matcher('123').matches(),\n" +
        "    pattern.matcher('abc').matches(),\n" +
        "  ];\n" +
        "}").executeVoid();
System.out.println(v8Runtime.getGlobalObject().invokeObject("main", pattern).toString());

/*
 * Output:
 *   [true, false]
 */

Inject a StringBuilder

v8Runtime.getGlobalObject().set("StringBuilder", StringBuilder.class);
 System.out.println(v8Runtime.getExecutor("function main() {\n" +
         "  return new StringBuilder('Hello').append(' from StringBuilder').toString();\n" +
         "}\n" +
         "main();").executeString());
 v8Runtime.getGlobalObject().delete("StringBuilder");

/*
 * Output:
 *   Hello from StringBuilder
 */

No comments:

Post a Comment

Cue Club 2 on Apple Silicon

It's been quite a long time for me not to play a decent snooker game since I replaced my Windows laptop with an Apple Silicon one. To be...