如果您需要预编译并使用各种参数调用 JavaSctipt 函数,您可以单独编译它们并在 Java 中组装执行流程。使用 Java8 中可用的 JavaScript 引擎 Nashorn,您可以:
private static final String FUNCTIONS =
"function hello( arg ) {" + //<-- passing java.lang.String from Java
" return 'Hello ' + arg;" + //<-- returning string back
"};" +
"function sayTime( arg ) {" + //<-- passing java.util.HashMap from Java
" return 'Java time ' + arg.get( 'time' );" + //<-- returning string back
"};" +
"function () {" + //<-- this callable "function pointer" is being returned on [step1] below
" return { 'hello': hello, 'sayTime': sayTime };" +
"};";
public static void main(String... args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName( "Nashorn" );
CompiledScript compiled = ((Compilable) engine).compile(FUNCTIONS);
ScriptObjectMirror lastFunction = (ScriptObjectMirror)compiled.eval(); // [step1]
ScriptObjectMirror functionTable = (ScriptObjectMirror)lastFunction.call( null ); // this method retrieves function table
String[] functionNames = functionTable.getOwnKeys( true );
System.out.println( "Function names: " + Arrays.toString( functionNames ) );
System.out.println( functionTable.callMember( "hello", "Robert" ) ); //<-- calling hello() with String as argiment
Map map = new HashMap();
map.put( "time", new Date().toString() ); //<-- preparing hashmap
System.out.println( functionTable.callMember( "sayTime", map ) ); //<-- calling sayTime() with HashMap as argument
}
您可以在 JavaSctipt 中传递 Java 对象,请参见上面的 java.util.HashMap 示例。
输出是:
Function names: [hello, sayTime]
Hello Robert
Java time Fri Jan 12 12:23:15 EST 2018