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 11var fun = function ( name ) {
2- print ( 'Hi there, ' + name ) ;
3- return "success " ;
2+ print ( 'Hi there from Javascript , ' + name ) ;
3+ return "greetings from javascript " ;
44} ;
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 33import javax .script .Invocable ;
44import javax .script .ScriptEngine ;
55import javax .script .ScriptEngineManager ;
6- import javax .script .ScriptException ;
7- import java .io .FileNotFoundException ;
86import java .io .FileReader ;
97
108/**
9+ * Calling javascript functions from java with nashorn.
10+ *
1111 * @author Benjamin Winterberg
1212 */
1313public class Nashorn1 {
1414
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" );
1817 engine .eval (new FileReader ("res/nashorn1.js" ));
1918
2019 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