我是Nashorn的新手,我正在尝试编写一个程序并尝试运行该程序,但是在运行程序后我得到了结果。请在下面找到我的代码。
package com.nashron;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class InvokScriptObjectMethod {
public static void main(String[] args){
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
try {
engine.eval(new FileReader("src/script/Script.js"));
} catch (ScriptException | FileNotFoundException ex) {
}
}
}
JS:
var Script = Java.type("com.nashron.Script");
var var1 = new Script("who am i");
return var1.get("I am Amar");
Java:
package com.nashron;
public class Script {
public Script() {
}
public Script(String arg1) {
this.var1 = arg1;
System.out.println("this is contructor");
}
private String var1;
public String get(String arg1) {
System.out.println("this is return statement");
return this.var1 + arg1;
}
}
这里我想获得返回值。
先谢谢
答案 0 :(得分:0)
顶级脚本无法返回"返回"声明。这符合ECMAScript规范。您的程序将导致抛出ScriptException - 因为您的JS代码中有一个return语句(在顶层)。如果只删除return,则从engine.eval调用返回最后一个计算表达式。
示例:
文件:Main.java
import javax.script.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
Object val = e.eval(new FileReader("x.js"));
System.out.println(val);
}
}
档案:x.js
java.lang.System.getProperty("os.name");