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

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

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

SimpleScriptContext 类的removeAttribute()方法用于删除给定范围内的属性,属性名称和范围作为参数传递。

句法:

public Object removeAttribute(String name, int scope)

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

  • name是属性的名称和
  • scope是删除属性的范围。

返回值:此方法返回移除的值。

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

  • NullPointerException :如果名称为空。
  • IllegalArgumentException :如果名称为空或范围无效。

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

// Java program to demonstrate
// SimpleScriptContext.removeAttribute() 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);
  
        // remove using removeAttribute()
        Object removedObject
            = simple.removeAttribute(
                "name",
                ScriptContext.ENGINE_SCOPE);
  
        // print
        System.out.println("Removed Object :"
                           + removedObject);
    }
}
输出:
Removed Object :Value

方案二:

// Java program to demonstrate
// SimpleScriptContext.removeAttribute() 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.ENGINE_SCOPE);
        simple.setAttribute("Team3", "Nepal",
                            ScriptContext.GLOBAL_SCOPE);
  
        // remove using removeAttribute()
        Object remove1
            = simple.removeAttribute(
                "Team1",
                ScriptContext.ENGINE_SCOPE);
        Object remove2
            = simple.removeAttribute(
                "Team2",
                ScriptContext.ENGINE_SCOPE);
  
        // print scopes of different teams
        System.out.println("Removed : " + remove1);
        System.out.println("Removed : " + remove2);
    }
}
输出:
Removed : India
Removed : Japan

参考:https://docs.oracle.com/javase/10/docs/api/javax/script/SimpleScriptContext.html#removeAttribute(Java.lang.String, int)