Skip to content

Commit f90fee0

Browse files
committed
calling a java method from javascript
1 parent fafa0e0 commit f90fee0

File tree

4 files changed

+33
-7
lines changed

4 files changed

+33
-7
lines changed

res/nashorn1.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
var fun = function(name) {
2-
print('Hi there, ' + name);
3-
return "success";
2+
print('Hi there from Javascript, ' + name);
3+
return "greetings from javascript";
44
};

res/nashorn2.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
var Nashorn2 = Java.type('com.winterbe.java8.Nashorn2');
2+
var result = Nashorn2.fun('John Doe');
3+
print('\n' + result);

src/com/winterbe/java8/Nashorn1.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,17 @@
33
import javax.script.Invocable;
44
import javax.script.ScriptEngine;
55
import javax.script.ScriptEngineManager;
6-
import javax.script.ScriptException;
7-
import java.io.FileNotFoundException;
86
import java.io.FileReader;
97

108
/**
9+
* Calling javascript functions from java with nashorn.
10+
*
1111
* @author Benjamin Winterberg
1212
*/
1313
public 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;

src/com/winterbe/java8/Nashorn2.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
}

0 commit comments

Comments
 (0)