File tree Expand file tree Collapse file tree 4 files changed +33
-7
lines changed Expand file tree Collapse file tree 4 files changed +33
-7
lines changed Original file line number Diff line number Diff line change 1
1
var fun = function ( name ) {
2
- print ( 'Hi there, ' + name ) ;
3
- return "success " ;
2
+ print ( 'Hi there from Javascript , ' + name ) ;
3
+ return "greetings from javascript " ;
4
4
} ;
Original file line number Diff line number Diff line change
1
+ var Nashorn2 = Java . type ( 'com.winterbe.java8.Nashorn2' ) ;
2
+ var result = Nashorn2 . fun ( 'John Doe' ) ;
3
+ print ( '\n' + result ) ;
Original file line number Diff line number Diff line change 3
3
import javax .script .Invocable ;
4
4
import javax .script .ScriptEngine ;
5
5
import javax .script .ScriptEngineManager ;
6
- import javax .script .ScriptException ;
7
- import java .io .FileNotFoundException ;
8
6
import java .io .FileReader ;
9
7
10
8
/**
9
+ * Calling javascript functions from java with nashorn.
10
+ *
11
11
* @author Benjamin Winterberg
12
12
*/
13
13
public class Nashorn1 {
14
14
15
- public static void main (String [] args ) throws ScriptException , FileNotFoundException , NoSuchMethodException {
16
- ScriptEngine engine = new ScriptEngineManager ()
17
- .getEngineByName ("nashorn" );
15
+ public static void main (String [] args ) throws Exception {
16
+ ScriptEngine engine = new ScriptEngineManager ().getEngineByName ("nashorn" );
18
17
engine .eval (new FileReader ("res/nashorn1.js" ));
19
18
20
19
Invocable invocable = (Invocable ) engine ;
Original file line number Diff line number Diff line change
1
+ package com .winterbe .java8 ;
2
+
3
+ import javax .script .ScriptEngine ;
4
+ import javax .script .ScriptEngineManager ;
5
+ import java .io .FileReader ;
6
+
7
+ /**
8
+ * Calling java methods from javascript with nashorn.
9
+ *
10
+ * @author Benjamin Winterberg
11
+ */
12
+ public class Nashorn2 {
13
+
14
+ public static String fun (String name ) {
15
+ System .out .format ("Hi there from Java, %s" , name );
16
+ return "greetings from java" ;
17
+ }
18
+
19
+ public static void main (String [] args ) throws Exception {
20
+ ScriptEngine engine = new ScriptEngineManager ().getEngineByName ("nashorn" );
21
+ engine .eval (new FileReader ("res/nashorn2.js" ));
22
+ }
23
+
24
+ }
You can’t perform that action at this time.
0 commit comments