Javet — Java and JavaScript Interop

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" +
* Output:
* Hello from Java
* Hello from JavaScript

Inject an Enum

v8Runtime.getGlobalObject().set("Color", Color.class);
System.out.println("The enum in JavaScript is the one in Java: " +
(Color.pink == (Color) v8Runtime.getExecutor("Color.pink;").executeObject()));
* 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" +
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" +
* Output:
* Hello from StringBuilder




Amateur programmer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

String algorithms in javascript

How to Get Started with D3.js

Creating a React JS Application Image with Packer and Ansible on Alibaba Cloud

How to build a calculator with JavaScript

Render dynamically a .docx file with JavaScript

Custom Directive with Angular mat-autocomplete

Top 4 Skills You Should Know as a Self-Taught Developer in 2022

7 Themes to Make Your VS Code Look Beautiful

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sam Cao

Sam Cao

Amateur programmer

More from Medium

Aberrations with character encoding in Chrome and Tomcat

Handling Protractor Control Flow Deprecation


Confused between AngularJS and ReactJS? Let’s make it simpler for you!

AngularJS and ReactJS