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

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

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

SimpleScriptContext 类的getAttributesScope()方法用于返回定义属性的范围,并将属性名称作为参数传递。

句法:

public int getAttributesScope(String name)

参数:此方法接受一个参数名称,即属性的名称。

返回值:如果在任何范围内没有定义具有给定名称的属性,则此方法返回最低范围并返回 -1。

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

  • 如果名称为空,则出现NullPointerException
  • 如果名称为空,则IllegalArgumentException

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

// Java program to demonstrate
// SimpleScriptContext.getAttributesScope() method
  
import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create SimpleScriptContext object
        SimpleScriptContext simple
            = new SimpleScriptContext();
  
        // add some attribute
        simple.setAttribute(
            "name",
            "Value",
            ScriptContext.ENGINE_SCOPE);
  
        // get scope using getAttributesScope()
        int scope = simple.getAttributesScope("name");
  
        // print
        System.out.println("Scope :" + scope);
    }
}
输出:
Scope :100

方案二:

// Java program to demonstrate
// SimpleScriptContext.getAttributesScope() method
  
import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create SimpleScriptContext object
        SimpleScriptContext simple
            = new SimpleScriptContext();
  
        // add some attribute
        simple.setAttribute(
            "Team1",
            "India",
            ScriptContext.ENGINE_SCOPE);
        simple.setAttribute(
            "Team2",
            "Japan",
            ScriptContext.GLOBAL_SCOPE);
        simple.setAttribute(
            "Team3",
            "Nepal",
            ScriptContext.GLOBAL_SCOPE);
  
        // get scope using getAttributesScope()
        int scope1
            = simple.getAttributesScope("Team1");
        int scope2
            = simple.getAttributesScope("Team2");
        int scope3
            = simple.getAttributesScope("Team3");
  
        // print scopes of different teams
        System.out.println("Scope for Team1: "
                           + scope1);
        System.out.println("Scope for Team2: "
                           + scope2);
        System.out.println("Scope for Team3: "
                           + scope3);
    }
}
输出:
Scope for Team1: 100
Scope for Team2: -1
Scope for Team3: -1

参考资料:https://docs.oracle.com/javase/10/docs/api/javax/script/ScriptContext.html