从文件中读取然后通过调用特定方法来执行Js代码

Reading from file then excetuing Js code by calling specific method

我制作了一些.txt个文件,里面只有JavaScript一个方法。例如code.txt的内容是:

function method(){

    return 4;

}

现在我想读取特定文件并执行java脚本代码

这是我试过的:

public class read {


    public static void main(String[] args) throws IOException, ScriptException {


        ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("js");

        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("code.txt")));

        String content ="";
        String code ="";

        while((content = bufferedReader.readLine())!=null){
            code+=content;
        }
        
        scriptEngine.eval(code);
    }
}

我想从 method() 中获取结果并检查返回值是否为 4

没有结果是 returned,因为 ScriptEngine 没有被告知 return 任何值和调用特定方法。在我们需要从另一个脚本调用方法的情况下我们会做什么当然我们会使用 INVOCABLE 接口接口的作用是调用在先前脚本执行期间编译的脚本对象上的方法,该脚本对象被保留在 ScriptEngine 的状态下所以在你的情况下你应该做的是将 scripEngine 类型转换为 Invocable

Invocable invocable = (Invocable)scriptEngine;

然后借助 invokeFunction 方法按名称调用您的函数

Object myResult =  invocable.invokeFunction("yourMethodName",null);

如果您想检查您的 returned 结果是否为 4,使用 if 条件应该很容易

if(myResult.equals(4)){
     //do something
}

您的代码已修复

public class read {


    public static void main(String[] args) throws IOException, ScriptException, NoSuchMethodException {


        ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("js");

        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("code.txt")));

        String content ="";
        String code ="";

        while((content = bufferedReader.readLine())!=null){
            code+=content;
        }

        Invocable invocable = (Invocable)scriptEngine;
        invocable.invokeFunction("yourMethodName",null);
        scriptEngine.eval(code);

       if(myResult.equals(4)){
     //do something
}
    }
}