美文网首页
System property 系统属性变量

System property 系统属性变量

作者: zh_harry | 来源:发表于2018-10-04 12:22 被阅读0次

    System property 概念

    The Java platform itself uses a Properties object to maintain its own configuration. The System class maintains a Properties object that describes the configuration of the current working environment. System properties include information about the current user, the current version of the Java runtime, and the character used to separate components of a file path name.

    在JAVA平台自身会使用一个Properties的对象来保存它自自己的配置."System"类保持了一个Properties对象,这个对象描述了当前工作环境的配置。这些配置包括当前用户,当前JVM版本及文件目录名的分隔离符等等.
    与系统环境变量不同,可以将System property理解为JVM的环境变量。

    原文链接

    设置属性变量

    • 由JVM通过initializeSystemClass方法和clinit 方法初始化.

    System 源码

    /**
     * The <code>System</code> class contains several useful class fields
     * and methods. It cannot be instantiated.
     *
     * <p>Among the facilities provided by the <code>System</code> class
     * are standard input, standard output, and error output streams;
     * access to externally defined properties and environment
     * variables; a means of loading files and libraries; and a utility
     * method for quickly copying a portion of an array.
    

    System 类提供了一些有用的字段和方法,这个类不能被实例化.
    System类提供了一些基础工具,这些工具包括标准输入,标准输出,和error输出流;
    访问一些外部定义的属性和环境变量,一个加载文件和包的方式,还有一个快速复制数组(或数据的一部分)的方法

    public final class System {
       /* register the natives via the static initializer.
        *
        * VM will invoke the initializeSystemClass method to complete
        * the initialization for this class separated from clinit.
        * Note that to use properties set by the VM, see the constraints
        * described in the initializeSystemClass method.
    
     注册一个native "initializeSystemClass"方法完成System类的初始化,和clint隔离开.
     注意,这里的properties的由VM设置的,可以看"initializeSystemClass"方法的限制描述.
     */
    
        private static native void registerNatives();
        static {
            registerNatives();
        }
    
    Don't let anyone instantiate this class 
    
    private构造函数 防止该类被实例化
    
        private System() {
        }
    
        public final static InputStream in = null;
    
        public final static PrintStream out = null;
    public final static PrintStream err = null;
    
        /**
         * System properties. The following properties are guaranteed to be defined:
         * <dl>
         * <dt>java.version         <dd>Java version number
         * <dt>java.vendor          <dd>Java vendor specific string
         * <dt>java.vendor.url      <dd>Java vendor URL
         * <dt>java.home            <dd>Java installation directory
         * <dt>java.class.version   <dd>Java class version number
         * <dt>java.class.path      <dd>Java classpath
         * <dt>os.name              <dd>Operating System Name
         * <dt>os.arch              <dd>Operating System Architecture
         * <dt>os.version           <dd>Operating System Version
         * <dt>file.separator       <dd>File separator ("/" on Unix)
         * <dt>path.separator       <dd>Path separator (":" on Unix)
         * <dt>line.separator       <dd>Line separator ("\n" on Unix)
         * <dt>user.name            <dd>User account name
         * <dt>user.home            <dd>User home directory
         * <dt>user.dir             <dd>User's current working directory
         * </dl>
         */
    
        private static Properties props;
        private static native Properties initProperties(Properties props);
    
        /**
         * Determines the current system properties.
         * <p>
         * First, if there is a security manager, its
         * <code>checkPropertiesAccess</code> method is called with no
         * arguments. This may result in a security exception.
         * <p>
         * The current set of system properties for use by the
         * {@link #getProperty(String)} method is returned as a
         * <code>Properties</code> object. If there is no current set of
         * system properties, a set of system properties is first created and
         * initialized. This set of system properties always includes values
         * for the following keys:
         * <table summary="Shows property keys and associated values">
         * <tr><th>Key</th>
         *     <th>Description of Associated Value</th></tr>
         * <tr><td><code>java.version</code></td>
         *     <td>Java Runtime Environment version</td></tr>
         * <tr><td><code>java.vendor</code></td>
         *     <td>Java Runtime Environment vendor</td></tr>
         * <tr><td><code>java.vendor.url</code></td>
         *     <td>Java vendor URL</td></tr>
         * <tr><td><code>java.home</code></td>
         *     <td>Java installation directory</td></tr>
         * <tr><td><code>java.vm.specification.version</code></td>
         *     <td>Java Virtual Machine specification version</td></tr>
         * <tr><td><code>java.vm.specification.vendor</code></td>
         *     <td>Java Virtual Machine specification vendor</td></tr>
         * <tr><td><code>java.vm.specification.name</code></td>
         *     <td>Java Virtual Machine specification name</td></tr>
         * <tr><td><code>java.vm.version</code></td>
         *     <td>Java Virtual Machine implementation version</td></tr>
         * <tr><td><code>java.vm.vendor</code></td>
         *     <td>Java Virtual Machine implementation vendor</td></tr>
         * <tr><td><code>java.vm.name</code></td>
         *     <td>Java Virtual Machine implementation name</td></tr>
         * <tr><td><code>java.specification.version</code></td>
         *     <td>Java Runtime Environment specification  version</td></tr>
         * <tr><td><code>java.specification.vendor</code></td>
         *     <td>Java Runtime Environment specification  vendor</td></tr>
         * <tr><td><code>java.specification.name</code></td>
         *     <td>Java Runtime Environment specification  name</td></tr>
         * <tr><td><code>java.class.version</code></td>
         *     <td>Java class format version number</td></tr>
         * <tr><td><code>java.class.path</code></td>
         *     <td>Java class path</td></tr>
         * <tr><td><code>java.library.path</code></td>
         *     <td>List of paths to search when loading libraries</td></tr>
         * <tr><td><code>java.io.tmpdir</code></td>
         *     <td>Default temp file path</td></tr>
         * <tr><td><code>java.compiler</code></td>
         *     <td>Name of JIT compiler to use</td></tr>
         * <tr><td><code>java.ext.dirs</code></td>
         *     <td>Path of extension directory or directories
         *         <b>Deprecated.</b> <i>This property, and the mechanism
         *            which implements it, may be removed in a future
         *            release.</i> </td></tr>
         * <tr><td><code>os.name</code></td>
         *     <td>Operating system name</td></tr>
         * <tr><td><code>os.arch</code></td>
         *     <td>Operating system architecture</td></tr>
         * <tr><td><code>os.version</code></td>
         *     <td>Operating system version</td></tr>
         * <tr><td><code>file.separator</code></td>
         *     <td>File separator ("/" on UNIX)</td></tr>
         * <tr><td><code>path.separator</code></td>
         *     <td>Path separator (":" on UNIX)</td></tr>
         * <tr><td><code>line.separator</code></td>
         *     <td>Line separator ("\n" on UNIX)</td></tr>
         * <tr><td><code>user.name</code></td>
         *     <td>User's account name</td></tr>
         * <tr><td><code>user.home</code></td>
         *     <td>User's home directory</td></tr>
         * <tr><td><code>user.dir</code></td>
         *     <td>User's current working directory</td></tr>
         * </table>
         * <p>
         * Multiple paths in a system property value are separated by the path
         * separator character of the platform.
         * <p>
         * Note that even if the security manager does not permit the
         * <code>getProperties</code> operation, it may choose to permit the
         * {@link #getProperty(String)} operation.
         *
         * @return     the system properties
         * @exception  SecurityException  if a security manager exists and its
         *             <code>checkPropertiesAccess</code> method doesn't allow access
         *              to the system properties.
         * @see        #setProperties
         * @see        java.lang.SecurityException
         * @see        java.lang.SecurityManager#checkPropertiesAccess()
         * @see        java.util.Properties
         */
        public static Properties getProperties() {
            SecurityManager sm = getSecurityManager();
            if (sm != null) {
                sm.checkPropertiesAccess();
            }
    
            return props;
        }
    
        /**
         * Returns the system-dependent line separator string.  It always
         * returns the same value - the initial value of the {@linkplain
         * #getProperty(String) system property} {@code line.separator}.
         *
         * <p>On UNIX systems, it returns {@code "\n"}; on Microsoft
         * Windows systems it returns {@code "\r\n"}.
         *
         * @return the system-dependent line separator string
         * @since 1.7
         */
        public static String lineSeparator() {
            return lineSeparator;
        }
    
        private static String lineSeparator;
    
        /**
         * Sets the system properties to the <code>Properties</code>
         * argument.
         * <p>
         * First, if there is a security manager, its
         * <code>checkPropertiesAccess</code> method is called with no
         * arguments. This may result in a security exception.
         * <p>
         * The argument becomes the current set of system properties for use
         * by the {@link #getProperty(String)} method. If the argument is
         * <code>null</code>, then the current set of system properties is
         * forgotten.
         *
         * @param      props   the new system properties.
         * @exception  SecurityException  if a security manager exists and its
         *             <code>checkPropertiesAccess</code> method doesn't allow access
         *              to the system properties.
         * @see        #getProperties
         * @see        java.util.Properties
         * @see        java.lang.SecurityException
         * @see        java.lang.SecurityManager#checkPropertiesAccess()
         */
        public static void setProperties(Properties props) {
            SecurityManager sm = getSecurityManager();
            if (sm != null) {
                sm.checkPropertiesAccess();
            }
            if (props == null) {
                props = new Properties();
                initProperties(props);
            }
            System.props = props;
        }
    
        /**
         * Gets the system property indicated by the specified key.
         * <p>
         * First, if there is a security manager, its
         * <code>checkPropertyAccess</code> method is called with the key as
         * its argument. This may result in a SecurityException.
         * <p>
         * If there is no current set of system properties, a set of system
         * properties is first created and initialized in the same manner as
         * for the <code>getProperties</code> method.
         *
         * @param      key   the name of the system property.
         * @return     the string value of the system property,
         *             or <code>null</code> if there is no property with that key.
         *
         * @exception  SecurityException  if a security manager exists and its
         *             <code>checkPropertyAccess</code> method doesn't allow
         *              access to the specified system property.
         * @exception  NullPointerException if <code>key</code> is
         *             <code>null</code>.
         * @exception  IllegalArgumentException if <code>key</code> is empty.
         * @see        #setProperty
         * @see        java.lang.SecurityException
         * @see        java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
         * @see        java.lang.System#getProperties()
         */
        public static String getProperty(String key) {
            checkKey(key);
            SecurityManager sm = getSecurityManager();
            if (sm != null) {
                sm.checkPropertyAccess(key);
            }
    
            return props.getProperty(key);
        }
    
      Initialize the system class.  Called after thread initialization.
     初始化System 类,在线程初始化之后被调用
    
        private static void initializeSystemClass() {
    
            // VM might invoke JNU_NewStringPlatform() to set those encoding
            // sensitive properties (user.home, user.name, boot.class.path, etc.)
            // during "props" initialization, in which it may need access, via
            // System.getProperty(), to the related system encoding property that
            // have been initialized (put into "props") at early stage of the
            // initialization. So make sure the "props" is available at the
            // very beginning of the initialization and all system properties to
            // be put into it directly.
            props = new Properties();
            initProperties(props);  //
    

    initialized by the VM
    被JVM初始化

            // There are certain system configurations that may be controlled by
            // VM options such as the maximum amount of direct memory and
            // Integer cache size used to support the object identity semantics
            // of autoboxing.  Typically, the library will obtain these values
            // from the properties set by the VM.  If the properties are for
            // internal implementation use only, these properties should be
            // removed from the system properties.
            //
            // See java.lang.Integer.IntegerCache and the
            // sun.misc.VM.saveAndRemoveProperties method for example.
            //
            // Save a private copy of the system properties object that
            // can only be accessed by the internal implementation.  Remove
            // certain system properties that are not intended for public access.
            sun.misc.VM.saveAndRemoveProperties(props);
    
    
            lineSeparator = props.getProperty("line.separator");
            sun.misc.Version.init();
    
            FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
            FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
            FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
            setIn0(new BufferedInputStream(fdIn));
            setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
            setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));
    
            // Load the zip library now in order to keep java.util.zip.ZipFile
            // from trying to use itself to load this library later.
            loadLibrary("zip");
    
            // Setup Java signal handlers for HUP, TERM, and INT (where available).
            Terminator.setup();
    
            // Initialize any miscellenous operating system settings that need to be
            // set for the class libraries. Currently this is no-op everywhere except
            // for Windows where the process-wide error mode is set before the java.io
            // classes are used.
            sun.misc.VM.initializeOSEnvironment();
    
            // The main thread is not added to its thread group in the same
            // way as other threads; we must do it ourselves here.
            Thread current = Thread.currentThread();
            current.getThreadGroup().add(current);
    
            // register shared secrets
            setJavaLangAccess();
    
            // Subsystems that are invoked during initialization can invoke
            // sun.misc.VM.isBooted() in order to avoid doing things that should
            // wait until the application class loader has been set up.
            // IMPORTANT: Ensure that this remains the last initialization action!
            sun.misc.VM.booted();
        }
    
    

    初始化变量列表

    index key value
    0 java.runtime.name Java(TM) SE Runtime Environment
    01 sun.boot.library.path C:\Program Files\Java\jdk1.8.0_181\jre\bin
    02 java.vm.version 25.181-b13
    03 java.vm.vendor Oracle Corporation
    04 java.vendor.url http://java.oracle.com/
    05 path.separator ;
    06 java.vm.name Java HotSpot(TM) 64-Bit Server VM
    07 file.encoding.pkg sun.io
    08 user.country CN
    09 user.script
    10 sun.java.launcher SUN_STANDARD
    11 sun.os.patch.level
    12 test 123
    13 java.vm.specification.name Java Virtual Machine Specification
    14 user.dir D:\sparrow\sparrow-shell
    15 java.runtime.version 1.8.0_181-b13
    16 java.awt.graphicsenv sun.awt.Win32GraphicsEnvironment
    17 java.endorsed.dirs C:\Program Files\Java\jdk1.8.0_181\jre\lib\endorsed
    18 os.arch amd64
    19 java.io.tmpdir C:\Users\LIZHI~1.ZHA\AppData\Local\Temp\
    20 line.separator \r\n
    21 java.vm.specification.vendor Oracle Corporation
    22 user.variant
    23 os.name Windows 10
    24 sun.jnu.encoding GBK
    25 java.library.path C:\Program Files\Java\jdk1.8.0_181\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;c:\Program Files\Git\cmd;D:\Go\bin;C:\Program Files\nodejs;C:\Users\lizhi.zhang01\AppData\Local\Microsoft\WindowsApps;D:\apache-maven-3.5.4-bin\apache-maven-3.5.4\bin;C:\Program Files\Git\bin;C:\Program Files\Java\jdk1.8.0_181\bin;D:\go-work-space\bin;D:\Go\bin;D:\apache-ant-1.9.13\bin;D:\Gradle\gradle-4.10\bin;C:\Users\lizhi.zhang01\AppData\Roaming\npm;;.
    26 java.specification.name Java Platform API Specification
    27 java.class.version 52.0
    28 sun.management.compiler HotSpot 64-Bit Tiered Compilers
    29 os.version 10.0
    30 user.home C:\Users\lizhi.zhang01
    31 user.timezone
    32 java.awt.printerjob sun.awt.windows.WPrinterJob
    33 file.encoding UTF-8
    34 java.specification.version 1.8
    35 java.class.path C:\Program Files\Java\jdk1.8.0_181\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_181\jre
    36 user.name lizhi.zhang01
    37 java.vm.specification.version 1.8
    38 sun.java.command com.sparrow.jdk.os.SystemProperty 1 2 3
    39 java.home C:\Program Files\Java\jdk1.8.0_181\jre
    40 sun.arch.data.model 64
    41 user.language zh
    42 java.specification.vendor Oracle Corporation
    43 awt.toolkit sun.awt.windows.WToolkit
    44 java.vm.info mixed mode
    45 java.version 1.8.0_181
    46 java.ext.dirs C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext;C:\Windows\Sun\Java\lib\ext
    47 sun.boot.class.path C:\Program Files\Java\jdk1.8.0_181\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_181\jre\classes;C:\Users\lizhi.zhang01.IntelliJIdea2018.1\system\captureAgent\debugger-agent-storage.jar
    48 java.vendor Oracle Corporation
    49 file.separator \
    50 java.vendor.url.bug http://bugreport.sun.com/bugreport/
    51 sun.io.unicode.encoding UnicodeLittle
    52 sun.cpu.endian little
    53 sun.desktop windows
    54 sun.cpu.isalist amd64
    • 由JAVA命令SET PROPERTY
    用法: java [-options] class [args...]
               (执行类)
       或  java [-options] -jar jarfile [args...]
               (执行 jar 文件)
    其中选项包括:
        -d32          使用 32 位数据模型 (如果可用)
        -d64          使用 64 位数据模型 (如果可用)
        -server       选择 "server" VM
                      默认 VM 是 server.
    
        -cp <目录和 zip/jar 文件的类搜索路径>
        -classpath <目录和 zip/jar 文件的类搜索路径>
                      用 ; 分隔的目录, JAR 档案
                      和 ZIP 档案列表, 用于搜索类文件。
        -D<名称>=<值>
                      设置系统属性
        -verbose:[class|gc|jni]
                      启用详细输出
        -version      输出产品版本并退出
        -version:<值>
                      警告: 此功能已过时, 将在
                      未来发行版中删除。
                      需要指定的版本才能运行
        -showversion  输出产品版本并继续
        -jre-restrict-search | -no-jre-restrict-search
                      警告: 此功能已过时, 将在
                      未来发行版中删除。
                      在版本搜索中包括/排除用户专用 JRE
        -? -help      输出此帮助消息
        -X            输出非标准选项的帮助
        -ea[:<packagename>...|:<classname>]
        -enableassertions[:<packagename>...|:<classname>]
                      按指定的粒度启用断言
        -da[:<packagename>...|:<classname>]
        -disableassertions[:<packagename>...|:<classname>]
                      禁用具有指定粒度的断言
        -esa | -enablesystemassertions
                      启用系统断言
        -dsa | -disablesystemassertions
                      禁用系统断言
        -agentlib:<libname>[=<选项>]
                      加载本机代理库 <libname>, 例如 -agentlib:hprof
                      另请参阅 -agentlib:jdwp=help 和 -agentlib:hprof=help
        -agentpath:<pathname>[=<选项>]
                      按完整路径名加载本机代理库
        -javaagent:<jarpath>[=<选项>]
                      加载 Java 编程语言代理, 请参阅 java.lang.instrument
        -splash:<imagepath>
                      使用指定的图像显示启动屏幕
    有关详细信息, 请参阅 http://www.oracle.com/technetwork/java/javase/documentation/index.html。
    

    示例代码

    -D<名称>=<值>
    设置系统属性
    java -Dtest=1234 com.sparrow.jdk.os.SystemProperty 1 2 3 4

    package com.sparrow.jdk.os;
    
    //https://docs.oracle.com/javase/specs/jvms/se7/html/
    
    /**
     * java -Dtest=1234 com.sparrow.jdk.os.SystemProperty  1 2 3 4
     */
    public class SystemProperty {
      
        public static void main(String[] args) {
            for(int i=0;i<args.length;i++){
                System.out.println(args[i]);
            }
            System.out.println(System.getProperty("test"));
            System.out.println(System.getProperty("user.home"));
        }
    }
    
    

    通过System.setProperty方法设置

     System.setProperty("test","test");
    
    

    ?

    clinit VS init 方法

    相关文章

      网友评论

          本文标题:System property 系统属性变量

          本文链接:https://www.haomeiwen.com/subject/oxdxaftx.html