forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNashorn7.java
More file actions
43 lines (32 loc) · 1.08 KB
/
Nashorn7.java
File metadata and controls
43 lines (32 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.winterbe.java8;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
* @author Benjamin Winterberg
*/
public class Nashorn7 {
public static class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLengthOfName() {
return name.length();
}
}
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("function foo(predicate, obj) { return !!(eval(predicate)); };");
Invocable invocable = (Invocable) engine;
Person person = new Person();
person.setName("Hans");
String predicate = "obj.getLengthOfName() >= 4";
Object result = invocable.invokeFunction("foo", predicate, person);
System.out.println(result);
}
}