Java中的 SimpleScriptContext setAttribute() 方法及示例
SimpleScriptContext 类的setAttribute()方法用于在给定范围内设置属性的值,其中属性名称、属性值和属性范围作为参数传递。如果范围是 GLOBAL_SCOPE 并且没有为 GLOBAL_SCOPE 设置绑定,则 setAttribute 调用是无操作的。
句法:
public void setAttribute(String name,
Object value, int scope)
参数:此方法接受三个参数:
- name是要设置的属性的名称,
- value是属性的值,并且
- scope是设置属性的范围。
返回值:此方法不返回任何内容。
异常:此方法抛出以下异常:
- NullPointerException :如果名称为空。
- IllegalArgumentException :如果名称为空或范围无效。
下面的程序说明了 SimpleScriptContext.setAttribute() 方法:
方案一:
// Java program to demonstrate
// SimpleScriptContext.setAttribute() 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 using setAttribute()
simple.setAttribute(
"name1", "Value1",
ScriptContext.ENGINE_SCOPE);
// print
System.out.println("name1:"
+ simple.getAttribute("name1"));
}
}
输出:
name1:Value1
方案二:
// Java program to demonstrate
// SimpleScriptContext.setAttribute() 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 using setAttribute()
simple.setAttribute("Team1", "India",
ScriptContext.ENGINE_SCOPE);
simple.setAttribute("Team2", "Japan",
ScriptContext.ENGINE_SCOPE);
simple.setAttribute("Team3", "Nepal",
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#setAttribute(Java.lang.String, Java.lang.Object, int)