Search code examples
javascriptscriptengine

Reading from file then excetuing Js code by calling specific method


I made some .txt files, which contains only one method of JavaScript. For example the content of code.txt is:

function method(){

    return 4;

}

Now I want to read specific file and execute java script code

This is what I have tried:

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);
    }
}

I want to get the result from the method() and check if returned value is 4


Solution

  • No result is returned because ScriptEngine is not being told to return any value and to invoke specific method. what would we do in situations where we would need to call a method from another script of course we would use INVOCABLE interface What the interface does is that Calls a method on a script object compiled during a previous script execution which is retained in the state of the ScriptEngine So in your case what you should do is typecast scripEngine to Invocable

    Invocable invocable = (Invocable)scriptEngine;
    

    then calling your function by name with the help of invokeFunction method

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

    if u want to check if your returned result was 4 that should be easy with an if condition

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

    Your code fixed

    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
    }
        }
    }