Java SimpleScriptContext set attribute

Description

Java SimpleScriptContext set attribute


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

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", 2020, ScriptContext.ENGINE_SCOPE);
    ctx.setAttribute("name", "Java", ScriptContext.GLOBAL_SCOPE);

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

    // Add two key-value pairs to the global scope bindings
    ctx.setAttribute("year", 1982, ScriptContext.GLOBAL_SCOPE);
    ctx.setAttribute("name", "Javascipt", ScriptContext.GLOBAL_SCOPE);

    // Get the value of year without specifying the scope
    int yearValue = (Integer) ctx.getAttribute("year");
    System.out.println("yearValue = " + yearValue);

    // Get the value of name
    String nameValue = (String) ctx.getAttribute("name");
    System.out.println("nameValue = " + nameValue);

    // Get the value of year from engine and global scopes
    int engineScopeYear = (Integer) ctx.getAttribute("year", ScriptContext.ENGINE_SCOPE);
    int globalScopeYear = (Integer) ctx.getAttribute("year", ScriptContext.GLOBAL_SCOPE);

    System.out.println("engineScopeYear = " + engineScopeYear);
    System.out.println("globalScopeYear = " + globalScopeYear);
  }//  w w  w .j av  a 2s.  c o m
}



PreviousNext

Related