SimpleScriptContext setAttribute() method in Java with Examples
The setAttribute() method of a SimpleScriptContext class is used to set the value of an attribute in a given scope where the name of the attribute, the value of attribute and scope of the attribute is passed as parameters. If the scope is GLOBAL_SCOPE and there are no Bindings is set for GLOBAL_SCOPE, then setAttribute call is a no-op.
Syntax:
public void setAttribute(String name,
Object value, int scope)
Parameters: This method accepts three-parameters:
- name which is the Name of the attribute to set,
- value which is the value of the attribute and
- scope which is the scope in which to set the attribute.
Return value: This method returns nothing.
Exceptions: This method throws following Exceptions:
- NullPointerException: if the name is null.
- IllegalArgumentException: if the name is empty or if the scope is invalid.
Below programs illustrate the SimpleScriptContext.setAttribute() method:
Program 1:
import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;
public class GFG {
public static void main(String[] args)
{
SimpleScriptContext simple
= new SimpleScriptContext();
simple.setAttribute(
"name1" , "Value1" ,
ScriptContext.ENGINE_SCOPE);
System.out.println( "name1:"
+ simple.getAttribute( "name1" ));
}
}
|
Program 2:
import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;
public class GFG {
public static void main(String[] args)
{
SimpleScriptContext simple
= new SimpleScriptContext();
simple.setAttribute( "Team1" , "India" ,
ScriptContext.ENGINE_SCOPE);
simple.setAttribute( "Team2" , "Japan" ,
ScriptContext.ENGINE_SCOPE);
simple.setAttribute( "Team3" , "Nepal" ,
ScriptContext.ENGINE_SCOPE);
System.out.println( "Team1:"
+ simple.getAttribute( "Team1" ));
System.out.println( "Team2:"
+ simple.getAttribute( "Team2" ));
System.out.println( "Team3:"
+ simple.getAttribute( "Team3" ));
}
}
|
Output:
Team1:India
Team2:Japan
Team3:Nepal
References: https://docs.oracle.com/javase/10/docs/api/javax/script/SimpleScriptContext.html#setAttribute(java.lang.String, java.lang.Object, int)
Last Updated :
29 Jan, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...