从 java 代码调用外部 javascript 函数

2022-08-31 21:01:46

通过使用Java Scripting API,我能够在Java中执行JavaScript。但是,有人可以解释一下我需要向此代码中添加什么才能调用C:/Scripts/Jsfunctions中的函数吗.js

import javax.script.*;

public class InvokeScriptFunction {
public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    // JavaScript code in a String
    String script1 = "function hello(name) {print ('Hello, ' + name);}";
    String script2 = "function getValue(a,b) { if (a===\"Number\") return 1; 
                     else return b;}";
    // evaluate script
    engine.eval(script1);
    engine.eval(script2);

    Invocable inv = (Invocable) engine;

    inv.invokeFunction("hello", "Scripting!!");  //This one works.      
 }
}

答案 1

使用 ScriptEngine.eval(java.io.Reader) 读取脚本

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), StandardCharsets.UTF_8));

Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("yourFunction", "param");

答案 2
try {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        System.out.println("okay1");
        FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
        System.out.println("okay2");
        if (fileInputStream != null){
         BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
         engine.eval(reader);
         System.out.println("okay3");
        // Invocable javascriptEngine = null;
         System.out.println("okay4");
        Invocable invocableEngine = (Invocable)engine;
         System.out.println("okay5");
         int x=0;
         System.out.println("invocableEngine is : "+invocableEngine);
         Object object = invocableEngine.invokeFunction("backend_message",x);

         System.out.println("okay6");
        }
        }catch(Exception e) {
            System.out.println("erroe when calling js function"+ e);
        }