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" +
"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
*/

--

--

--

Amateur programmer

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

Recommended from Medium

🔖 Banggood sale

Learning JavaScript: A Sequential Theory of Instruction

Javascript

Advance javascript and Es6 some important topics.

How to Include Star Rating Component in React Native

Here Are the Most Common JavaScript Algorithms and Data Structures

Theming guide in React with Material-UI (and styled-components)

How to use Linting tools in Vue.js/Nuxt

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

Java String.replace vs Javascript String.prototype.replace

Java vs JavaScript | Detailed comparison | All-time-dev

Java vs JavaScript

Handling Protractor Control Flow Deprecation

Array Algorithm: Rotate an image