提交 10e80025 编写于 作者: B Benjamin Winterberg

Add another nashorn sample of dynamically invoking java code at runtime

上级 a5aeb321
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);
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册