当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java SimpleScriptContext setAttribute()用法及代码示例


SimpleScriptContext类的setAttribute()方法用于在给定范围内设置属性的值,其中属性名称,属性值和属性范围作为参数传递。如果范围是GLOBAL_SCOPE,并且没有为GLOBAL_SCOPE设置绑定,则setAttribute调用是no-op。

用法:

public void setAttribute(String name,
       Object value, int scope)

参数:此方法接受three-parameters:


  • name这是要设置的属性的名称,
  • value这是属性的值,
  • scope这是设置属性的范围。

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

异常:此方法引发以下异常:

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

以下示例程序旨在说明SimpleScriptContext.setAttribute()方法:
程序1:

// 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

程序2:

// 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)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 SimpleScriptContext setAttribute() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。