Skip to content

Commit 7d8c0cc

Browse files
committed
playing around with nashorn javascript extensions
1 parent 3d559e5 commit 7d8c0cc

File tree

3 files changed

+89
-1
lines changed

3 files changed

+89
-1
lines changed

res/nashorn3.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,4 +104,22 @@ new Thread(new Printer()).start();
104104

105105
new Thread(function() {
106106
print('this was printed from another thread');
107-
}).start();
107+
}).start();
108+
109+
110+
print('------------------');
111+
print('Parameter Overload:');
112+
113+
var System = Java.type('java.lang.System');
114+
115+
System.out.println(10);
116+
System.out["println"](11.0);
117+
System.out["println(double)"](12);
118+
119+
print('------------------');
120+
print('JavaBeans:');
121+
122+
var Date = Java.type('java.util.Date');
123+
var date = new Date();
124+
date.year += 1900;
125+
System.out.println(date.year);

res/nashorn4.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// function literal with no braces
2+
3+
function sqr(x) x * x;
4+
5+
print(sqr(3));
6+
7+
8+
// for each
9+
10+
var array = [1, 2, 3, 4];
11+
for each (var num in array) print(num);
12+
13+
14+
// object literals in constructors
15+
16+
var runnable = new java.lang.Runnable() {
17+
run: function() {
18+
print('on the run');
19+
}
20+
};
21+
22+
runnable.run();
23+
24+
25+
// bind properties
26+
27+
var o1 = {};
28+
var o2 = { foo: 'bar'};
29+
30+
Object.bindProperties(o1, o2);
31+
32+
print(o1.foo);
33+
o1.foo = 'BAM';
34+
print(o2.foo);
35+
36+
37+
// string trim
38+
39+
print(" hehe".trimLeft());
40+
print("hehe ".trimRight() + "he");
41+
42+
43+
// whereis
44+
print(__FILE__, __LINE__, __DIR__);
45+
46+
47+
// java import
48+
49+
var imports = new JavaImporter(java.util, java.io);
50+
with (imports) {
51+
var map = new HashMap();
52+
}

src/com/winterbe/java8/Nashorn4.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.winterbe.java8;
2+
3+
import javax.script.ScriptEngine;
4+
import javax.script.ScriptEngineManager;
5+
6+
/**
7+
* Working with java types from javascript.
8+
*
9+
* @author Benjamin Winterberg
10+
*/
11+
public class Nashorn4 {
12+
13+
public static void main(String[] args) throws Exception {
14+
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
15+
engine.eval("loadWithNewGlobal('res/nashorn4.js')");
16+
}
17+
18+
}

0 commit comments

Comments
 (0)