📜  Java中的 SimpleBindings get() 方法及示例

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

Java中的 SimpleBindings get() 方法及示例

SimpleBindings 类get()方法用于返回此 SimpleBindings 对象将作为参数传递的键映射到的值。如果 SimpleBindings 对象不包含此键的映射,则该方法返回 null。

句法:

public Object get(Object key)

参数:此方法只接受一个参数,该键是要返回其关联值的键。

返回值:此方法返回此键映射到的值,或 null。

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

  • NullPointerException : 如果键为空
  • ClassCastException : 如果键不是字符串
  • IllegalArgumentException : 如果键为空字符串

说明 get() 方法工作的Java程序:

方案一:

// Java program to demonstrate get() method
  
import javax.script.SimpleBindings;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create simpleBindings object
        SimpleBindings bindings
            = new SimpleBindings();
  
        // add some keys with values
        bindings.put("key1", "value1");
        bindings.put("key2", "value2");
        bindings.put("key3", "value3");
  
        // get value of key3
        Object value = bindings.get("key3");
  
        // print
        System.out.println("key3 value: "
                           + value);
    }
}
输出:
key3 value: value3

方案二:

// Java program to demonstrate get() method
  
import javax.script.SimpleBindings;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create simpleBindings object
        SimpleBindings asiaTeamList
            = new SimpleBindings();
  
        // add team in asiaTeamList
        asiaTeamList.put("team1", "India");
        asiaTeamList.put("team2", "Sri Lanka");
        asiaTeamList.put("team3", "Pakistan");
        asiaTeamList.put("team4", "Bangladesh");
  
        // get team1, team2 and team5 values
        Object team1 = asiaTeamList.get("team1");
        Object team2 = asiaTeamList.get("team2");
        Object team5 = asiaTeamList.get("team5");
  
        // print team names
        System.out.println("Team1 :"
                           + team1);
        System.out.println("Team2 :"
                           + team2);
        System.out.println("Team5 :"
                           + team5);
    }
}
输出:
Team1 :India
Team2 :Sri Lanka
Team5 :null

参考资料: https://docs.oracle.com/javase/10/docs/api/javax/script/SimpleBindings.html#get(Java.lang.Object)