Java System getProperty() 方法



描述

Java System getProperty(String key, String def) 方法獲取由指定key指示的系統屬性。引數def是預設值。

宣告

以下是java.lang.System.getProperty()方法的宣告

public static String getProperty(String key, String def)

引數

  • key - 這是系統屬性的名稱。

  • def - 這是預設值。

返回值

此方法返回系統屬性的字串值,如果不存在具有該鍵的屬性,則返回 null。

異常

  • SecurityException - 如果存在安全管理器並且其 checkPropertyAccess 方法不允許訪問指定的系統屬性。

  • NullPointerException - 如果 key 為 null。

  • IllegalArgumentException - 如果 key 為空。

示例:如果系統屬性不存在則獲取預設值

以下示例顯示了 Java System getProperty() 方法的使用。在此示例中,我們使用了不存在的鍵 password。由於鍵不存在,System.getProperty() 方法返回作為引數傳遞的預設值,並打印出來。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) {

      // gets the system property 
      System.out.println(System.getProperty("password","defaultPassword")); 
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

defaultPassword

示例:如果系統屬性存在則獲取值

以下示例顯示了 Java System getProperty() 方法的使用。在此示例中,我們使用了存在的鍵 password。由於鍵存在,System.getProperty() 方法返回可用值。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) {

      // gets the system property 
      System.out.println(System.getProperty("user.name","user")); 
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Tutorialspoint
java_lang_system.htm
廣告