6

I want to call the Javascript inside my Java class but not able to find correct way. I read somewhere it can be done using Nashorn. could someone please let me know the exact way.

3
  • 1
    Upvoters...any specific reason for upvoting this question? Commented Jun 4, 2018 at 13:20
  • 1
    No Idea Sir, any issues? Commented Jun 6, 2018 at 13:30
  • 1
    Nothing personal.. just wanted to know on what basis people are upvoting a question. Commented Jun 6, 2018 at 13:36

1 Answer 1

9

You can call JavaScript using "ScriptEngineManager" as below.

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine engine = scriptEngineManager.getEngineByName("nashorn");
    try {
        engine.eval(new FileReader("src\\demo.js"));
        Invocable invocable = (Invocable)engine;
        Object result = invocable.invokeFunction("fun1", "User");
        System.out.println(result);

    } catch (ScriptException e) {
        e.printStackTrace();
    }

And you JS file demo.js will looks something like below.

var fun1 = function(name){
print('Hi,'+name);
return "Greeting from javascript";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.