Tuesday Jan 20, 2009

Writing Java Script in Java.

A small code that can call JS code from within Java.
This feature is part of the jdk6 version.









01 import javax.script.\*;
02 import java.util.\*;
03
04 class Sample
05 {
06 public static void main(String[] args)
07 {
08
09 ScriptEngineManager manager= new ScriptEngineManager();
10 List<ScriptEngineFactory> factories= manager.getEngineFactories();
11
12 for (ScriptEngineFactory factory: factories) {
13
14 String name = factory.getEngineName();
15 String version = factory.getEngineVersion();
16 String language = factory.getLanguageName();
17
18 System.out.println(name+"("+version+"): "+language);
19
20 for(String n: factory.getNames())
21 System.out.println(n);
22 }
23
24 // JavaScript code in a String
25 String script = "function hello(name) { print('Hello, ' + name); }";
26
27
28 ScriptEngine engine = manager.getEngineByName("JavaScript");
29
30 try
31 {
32 // evaluate JavaScript code from String
33 engine.eval("print('Hello, World')");
34 engine.eval(script);
35 Invocable inv = (Invocableengine;
36 inv.invokeFunction("hello""THE");
37
38 }
39 catch (ScriptException e)
40 {
41 e.printStackTrace();
42 }
43 catch (NoSuchMethodException ee){
44 ee.printStackTrace();
45 }
46
47
48 }
49 }

About

I am Vikram Aroskar working in the Java team based out of India.

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today