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
广告

© . All rights reserved.