Using an Instance of the ScriptContext Interface - Java Scripting

Java examples for Scripting:Run Script

Description

Using an Instance of the ScriptContext Interface

Demo Code

import java.util.List;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.SimpleBindings;
import javax.script.SimpleScriptContext;
import static javax.script.ScriptContext.ENGINE_SCOPE;
import static javax.script.ScriptContext.GLOBAL_SCOPE;

public class Main {
  public static void main(String[] args) {
    ScriptContext ctx = new SimpleScriptContext();
    List<Integer> scopes = ctx.getScopes();
    System.out.println("Supported Scopes: " + scopes);

    ctx.setAttribute("year", 2018, ENGINE_SCOPE);
    ctx.setAttribute("month", 9, ENGINE_SCOPE);
    ctx.setAttribute("day", 19, ENGINE_SCOPE);

    Bindings globalBindings = new SimpleBindings();
    ctx.setBindings(globalBindings, GLOBAL_SCOPE);

    ctx.setAttribute("year", 2018, GLOBAL_SCOPE);
    ctx.setAttribute("name", "Test", GLOBAL_SCOPE);

    int yearValue = (Integer)ctx.getAttribute("year");
    System.out.println("yearValue = " + yearValue);

    String nameValue = (String)ctx.getAttribute("name");
    System.out.println("nameValue = " + nameValue);

    int engineScopeYear = (Integer)ctx.getAttribute("year", ENGINE_SCOPE);
    int globalScopeYear = (Integer)ctx.getAttribute("year", GLOBAL_SCOPE);

    System.out.println("engineScopeYear = " + engineScopeYear);
    System.out.println("globalScopeYear = " + globalScopeYear);
  }/*from www  .j a va  2s  .c  om*/
}

Result


Related Tutorials