File tree 2 files changed +42
-1
lines changed
2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change 1
1
var Nashorn2 = Java . type ( 'com.winterbe.java8.Nashorn2' ) ;
2
2
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 ) ;
Original file line number Diff line number Diff line change 1
1
package com .winterbe .java8 ;
2
2
3
+ import jdk .nashorn .api .scripting .ScriptObjectMirror ;
4
+
3
5
import javax .script .ScriptEngine ;
4
6
import javax .script .ScriptEngineManager ;
5
7
import java .io .FileReader ;
8
+ import java .util .Arrays ;
6
9
7
10
/**
8
11
* Calling java methods from javascript with nashorn.
@@ -16,6 +19,18 @@ public static String fun(String name) {
16
19
return "greetings from java" ;
17
20
}
18
21
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
+
19
34
public static void main (String [] args ) throws Exception {
20
35
ScriptEngine engine = new ScriptEngineManager ().getEngineByName ("nashorn" );
21
36
engine .eval (new FileReader ("res/nashorn2.js" ));
You can’t perform that action at this time.
0 commit comments