📜  Java中的 SimpleScriptContext setBindings() 方法及示例

📅  最后修改于: 2022-05-13 01:55:20.333000             🧑  作者: Mango

Java中的 SimpleScriptContext setBindings() 方法及示例

SimpleScriptContext 类的setBindings()方法用于为给定范围设置属性绑定,其中绑定和范围作为参数传递给该方法。如果范围是 ENGINE_SCOPE,则给定的 Bindings 将替换 engineScope 字段。如果范围是 GLOBAL_SCOPE,则给定的 Bindings 将替换 globalScope 字段。

句法:

public void setBindings(Bindings bindings,
                        int scope)

参数:此方法接受两个参数:

  • bindings是要设置的属性的绑定,并且
  • scope是设置属性的范围。

返回值:此方法不返回任何内容。

异常:此方法抛出以下异常:

  • NullPointerException : 如果 scope 的值为 ENGINE_SCOPE 并且指定的 Bindings 为 null。
  • IllegalArgumentException :如果范围无效。

下面的程序说明了 SimpleScriptContext.setBindings() 方法:
方案一:

// Java program to demonstrate
// SimpleScriptContext.setBindings() method
  
import javax.script.ScriptContext;
import javax.script.SimpleBindings;
import javax.script.SimpleScriptContext;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create SimpleScriptContext object
        SimpleScriptContext simple
            = new SimpleScriptContext();
  
        // create Bindings
        SimpleBindings bindings
            = new SimpleBindings();
  
        // add some key-value to bindings
        bindings.put("name1", "Value1");
  
        // add bindings to SimpleScriptContext using
        // setBindings() Method
        simple.setBindings(
            bindings,
            ScriptContext.ENGINE_SCOPE);
  
        // print
        System.out.println(
            "name1:"
            + simple.getAttribute("name1"));
    }
}
输出:
name1:Value1

方案二:

// Java program to demonstrate
// SimpleScriptContext.setBindings() method
  
import javax.script.ScriptContext;
import javax.script.SimpleBindings;
import javax.script.SimpleScriptContext;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create SimpleScriptContext object
        SimpleScriptContext simple
            = new SimpleScriptContext();
  
        // create Bindings
        SimpleBindings bindings
            = new SimpleBindings();
  
        // add some key-value to bindings
        bindings.put("Team1", "India");
        bindings.put("Team2", "Japan");
        bindings.put("Team3", "Nepal");
  
        // add bindings to SimpleScriptContext using
        // setBindings() Method
        simple.setBindings(
            bindings,
            ScriptContext.ENGINE_SCOPE);
  
        // print
        System.out.println("Team1:"
                           + simple.getAttribute("Team1"));
        System.out.println("Team2:"
                           + simple.getAttribute("Team2"));
        System.out.println("Team3:"
                           + simple.getAttribute("Team3"));
    }
}
输出:
Team1:India
Team2:Japan
Team3:Nepal

参考:https://docs.oracle.com/javase/10/docs/api/javax/script/SimpleScriptContext.html#setBindings(javax.script.Bindings, int)