Accessing Script Global Variables in Java Code - Java Scripting

Java examples for Scripting:Run Script

Description

Accessing Script Global Variables in Java Code

Demo Code

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    String script = "var year = 2018";

    try {/*  w  w  w  . j a  v  a  2s  .co  m*/
      engine.eval(script);
      Object year = engine.get("year");
      System.out.println("year's class:" +
        year.getClass().getName());
      System.out.println("year's value:" + year);
    }
    catch (ScriptException e) {
      e.printStackTrace();
    }
  }
}

Result


Related Tutorials