Example of interaction between ScriptEngine and javascript in java (New Features of JDK 6)

Source: Internet
Author: User

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 );
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.