Skip to content

Commit 3d559e5

Browse files
committed
pass js objects to java and work with properties and members on java side
1 parent a6168ec commit 3d559e5

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

res/nashorn2.js

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,29 @@
11
var Nashorn2 = Java.type('com.winterbe.java8.Nashorn2');
22
var result = Nashorn2.fun('John Doe');
3-
print('\n' + result);
3+
print('\n' + result);
4+
5+
Nashorn2.fun2(new Date());
6+
Nashorn2.fun2(new RegExp());
7+
Nashorn2.fun2({foo: 'bar'});
8+
9+
10+
print('passing object hash:');
11+
Nashorn2.fun3({
12+
foo: 'bar',
13+
bar: 'foo'
14+
});
15+
16+
17+
print('passing custom person object:');
18+
19+
function Person(firstName, lastName) {
20+
this.firstName = firstName;
21+
this.lastName = lastName;
22+
this.getFullName = function() {
23+
return this.firstName + " " + this.lastName;
24+
}
25+
}
26+
27+
var person1 = new Person("Peter", "Parker");
28+
Nashorn2.fun3(person1);
29+
Nashorn2.fun4(person1);

src/com/winterbe/java8/Nashorn2.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package com.winterbe.java8;
22

3+
import jdk.nashorn.api.scripting.ScriptObjectMirror;
4+
35
import javax.script.ScriptEngine;
46
import javax.script.ScriptEngineManager;
57
import java.io.FileReader;
8+
import java.util.Arrays;
69

710
/**
811
* Calling java methods from javascript with nashorn.
@@ -16,6 +19,18 @@ public static String fun(String name) {
1619
return "greetings from java";
1720
}
1821

22+
public static void fun2(Object object) {
23+
System.out.println(object.getClass());
24+
}
25+
26+
public static void fun3(ScriptObjectMirror mirror) {
27+
System.out.println(mirror.getClassName() + ": " + Arrays.toString(mirror.getOwnKeys(true)));
28+
}
29+
30+
public static void fun4(ScriptObjectMirror person) {
31+
System.out.println("Full Name is: " + person.callMember("getFullName"));
32+
}
33+
1934
public static void main(String[] args) throws Exception {
2035
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
2136
engine.eval(new FileReader("res/nashorn2.js"));

0 commit comments

Comments
 (0)