Java ScriptEngine create parameter binding

Description

Java ScriptEngine create parameter binding

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

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

    // Do not instantiate SimpleBindings class directly.
    // Use the createBindings() method of the engine to create a Bindings.
    Bindings params = engine.createBindings();

    // Create a Bindings instance
    // Bindings params = new SimpleBindings();

    // Add some key-value pairs
    params.put("msg", "Hello");
    params.put("year", 1969);

    // Get values
    Object msg = params.get("msg");
    Object year = params.get("year");
    System.out.println("msg = " + msg);
    System.out.println("year = " + year);

    // Remove year from Bindings
    params.remove("year");
    year = params.get("year");

    boolean containsYear = params.containsKey("year");
    System.out.println("year = " + year);
    System.out.println("params contains year = " + containsYear);
  }//from w  ww .  j a v a  2s.  c o  m
}



PreviousNext

Related