Example of using ScriptEngine to interact with javascript in java (New Features of JDK 6)
Code:
Package demo7;
Import java. util. Arrays;
Import java. util. List;
Import javax. script. Invocable;
Import javax. script. ScriptEngine;
Import javax. script. ScriptEngineManager;
Public class ScriptEngineTest {
Public static void main (String [] args) throws Exception {
ScriptEngineManager sem = new ScriptEngineManager ();
ScriptEngine engine = sem. getEngineByName ("javascript ");
// 1
Engine. put ("msg", "just a test ");
String str = "msg + = '!!! '; Var user = {name: 'Tom', age: 23, hobbies: ['football', 'bucketball ']}; var name = user. name; var hb = user. hobbies [1]; ";
Engine. eval (str );
String msg = (String) engine. get ("msg ");
String name = (String) engine. get ("name ");
String hb = (String) engine. get ("hb ");
System. out. println (msg );
System. out. println (name + ":" + hb );
// 2
Engine. eval ("function add (a, B) {c = a + B; return c ;}");
Invocable jsInvoke = (Invocable) engine;
Object result1 = jsInvoke. invokeFunction ("add", new Object [] {10, 5 });
System. out. println (result1 );
// 3
Adder adder = jsInvoke. getInterface (Adder. class );
Int result2 = adder. add (10, 35 );
System. out. println (result2 );
// 4
Engine. eval ("function run () {print ('www .java2s.com ');}");
Invocable invokeEngine = (Invocable) engine;
Runnable runner = invokeEngine. getInterface (Runnable. class );
Thread t = new Thread (runner );
T. start ();
T. join ();
// 5
String jsCode = "importPackage (java. util); var list2 = Arrays. asList (['A', 'B', 'C']);";
Engine. eval (jsCode );
List <String> list2 = (List <String>) engine. get ("list2 ");
For (String val: list2 ){
System. out. println (val );
}
}
}
Interface Adder {
Int add (int a, int B );
}