Invoking a Method on an Object Created in Nashorn JavaScript - Java Scripting

Java examples for Scripting:Run Script

Description

Invoking a Method on an Object Created in Nashorn JavaScript

Demo Code

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class Main {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    if (!(engine instanceof Invocable)) {
      System.out.println("Invoking methods is not supported.");
      return;//from   ww  w.j  a v a  2s  .  c o  m
    }
    Invocable inv = (Invocable) engine;

    String script = "var calculator = new Object();"
        + "calculator.add = function add(n1, n2){return n1 + n2;}";
    engine.eval(script);
    Object calculator = engine.get("calculator");
    Object result = inv.invokeMethod(calculator, "add", 3, 4);
    System.out.println("Result = " + result);
  }
}

Result


Related Tutorials