Skip to content

Commit a6168ec

Browse files
committed
pass java objects to javascript functions
1 parent 28983b4 commit a6168ec

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

res/nashorn1.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
var fun = function(name) {
1+
var fun1 = function(name) {
22
print('Hi there from Javascript, ' + name);
33
return "greetings from javascript";
4+
};
5+
6+
var fun2 = function (object) {
7+
print("JS Class Definition: " + Object.prototype.toString.call(object));
48
};

src/com/winterbe/java8/Nashorn1.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import javax.script.ScriptEngine;
55
import javax.script.ScriptEngineManager;
66
import java.io.FileReader;
7+
import java.time.LocalDateTime;
8+
import java.util.Date;
79

810
/**
911
* Calling javascript functions from java with nashorn.
@@ -17,8 +19,12 @@ public static void main(String[] args) throws Exception {
1719
engine.eval(new FileReader("res/nashorn1.js"));
1820

1921
Invocable invocable = (Invocable) engine;
20-
Object result = invocable.invokeFunction("fun", "Peter Parker");
22+
Object result = invocable.invokeFunction("fun1", "Peter Parker");
2123
System.out.println(result);
24+
25+
invocable.invokeFunction("fun2", new Date());
26+
invocable.invokeFunction("fun2", LocalDateTime.now());
27+
invocable.invokeFunction("fun2", new Person());
2228
}
2329

2430
}

0 commit comments

Comments
 (0)