Ticker

6/recent/ticker-posts

Java 8 example: call between Java and Javascript

This example show how to call Javascript function from Java, and call Java method from Javascript.


JavaTryJavaScript.java
package javatryjavascript;

import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JavaTryJavaScript {

final static String myJavascript = "/home/pi/testJS/newjavascript.js";

public static void main(String[] args)
throws FileNotFoundException, ScriptException, NoSuchMethodException {
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine nashornEngine = scriptEngineManager.getEngineByName("nashorn");

FileReader fileReader = new FileReader(myJavascript);
nashornEngine.eval(fileReader);

Invocable invocable = (Invocable)nashornEngine;
invocable.invokeFunction("testJavaScript1", "Hello from Java");

}

public static void JavaCalledFromJS(String s){
System.out.println("Java method called from JavaScript: " + s);
}

}

The Javascript in a separated file, /home/pi/testJS/newjavascript.js
var testJavaScript1 = function(a){
print('testJavaScript1, called from Java: ' + a);
testJavaScript2();
return;
}

var testJavaScript2 = function(){
print('testJavaScript2');
var javaClass = Java.type("javatryjavascript.JavaTryJavaScript");
javaClass.JavaCalledFromJS("message from JavaScript");
return;
}

إرسال تعليق

0 تعليقات