當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。