Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return boolean value after a javaScript code is evaluated using javax.script.ScriptEngine object

I am using javax.script.* package to evaluate javascript in a Java File. I am using a ScriptEngine object to evaluate some javaScript code. The javaScript code returns a Boolean value. I am not sure how to capture the boolean value in the Java file. For e.g., see:

import javax.script.*;
public class Test {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        String filepath = "../test.js";
        engine.eval(new java.io.FileReader(filepath));
    }
}

test.js

function test(value) {
    if(value==1) {
       println("True");
       return true;
    } else {
       println("False");
       return false;
    }
}

var i=1;
test (i);

I tried the following:

Boolean result = (Boolean) engine.eval(new java.io.FileReader(filepath));

The above line throws java.lang.NullPointerException error.

Thanks, Sony

like image 410
sony Avatar asked Mar 14 '26 23:03

sony


1 Answers

In JS:

var result=test (i);

In Java

engine.eval....
engine.get("result");
like image 139
alberlau Avatar answered Mar 16 '26 12:03

alberlau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!