Home > Java > javaTutorial > body text

In-depth analysis of java-System system class

黄舟
Release: 2017-05-07 09:40:46
Original
1299 people have browsed it

Tiantian said to use System.out.println for output, so I have a small question to ask, is out a variable or an internal class? Large and systematic knowledge is explained in detail in various topics. We cannot ignore these scattered knowledge points, otherwise it will be very embarrassing if we are asked such a simple question during the interview and cannot answer it.

Non-instantiable System class

System is a system class. In the java.lang package of JDK, it can be seen that it is also a core language of java. characteristic. The constructor of the System class is decorated with private and is not allowed to be instantiated. Therefore, the methods in the class are also static modified static methods.

Field

public final static InputStream in;
//标准输入流
public final static PrintStream out;
//标准输出流
public final static PrintStream err;
//标准错误流
Copy after login

It can be seen that out and in in System are not internal classes, but genuine field variables. out is the variable field modified by PrintStream's final static, which means it can call methods of the PrintStream class. Println is an output method of PrintStream, so we usually use System.out.println() to output content on the console.

Commonly used methods in System

arraycopy—— ArrayCopy

  public static void main(String[] args) {

        int[] arr1 = { 0, 1, 2, 3, 4 };
        int[] arr2 = { 9, 9, 9, 9, 9 };

        System.arraycopy(arr1, 2, arr2, 0, 3);

        arr1[3] = 8;

        for (int i = 0; i < 5; i++)
            System.out.print(arr2[i] + " ");
            //2 3 4 9 9 
    }
Copy after login

The arraycopy method has five parameters, which are the array to be copied, the starting position to be copied, the array to copy to, the starting position of the array to copy, and the copy to the end of this array. This method is similar to copyOf and copyOfRange in Arrays. It has more parameters and can be used if necessary.

currentTimeMillis——Return the number of milliseconds

I won’t give an example here, the currentTimeMillis method and the getTime method in the Date class It's exactly the same, if you just need milliseconds, such a call is also very convenient. However, it should be noted that currentTimeMillis does not directly get the result of getTime. currentTimeMillis is a local method that returns the time of the operating system. Since the minimum accuracy of the time of some operating systems is 10 milliseconds, this method may cause some deviations. .

getProperty——Get the system attribute

We call this method and enter the key ## in the parameter #StringGet system properties.

##java.version Java Runtime Environment Versionjava.vendorJava Runtime Environment Vendorjava.vendor.urlJava Provider URLjava.homeJava java.vm.specification.versionJava Virtual Machine Specification Versionjava.vm.specification.vendorJava Virtual Machine Specification Supply Businessjava.vm.specification.nameJava virtual machine specification namejava.vm.versionJava virtual machine implementation versionjava.vm.vendorJava virtual machine implementation vendor java.vm.nameJava virtual machine implementation namejava.specification.versionJava runtime environment specification versionjava.specification.vendorJava Runtime Environment Specification Vendorjava.specification.nameJava Runtime Environment specification namejava.Java class format version number java.class.pathJava class pathjava.library.pathList of paths to search java.io.tmpdirjava.compilerjava.ext.dirs os.nameos.archArchitecture of the operating systemos.versionfilepath.separatorline.separatoruser.nameuser.homeuser.dir

在我们操作文件的时候很可能需要使用到我们的当前工作目录,可以用这个方法来获得。

  public static void main(String[] args) {
        String dirPath = System.getProperty("user.dir");
        System.out.println(dirPath);
        //输出工作目录  D:\Workspaces\MyEclipse 10\Algorithms(这是我的目录,每个人都不同)
    }
Copy after login

上面的表中就不再举例了,比较常用的是后几个key

gc——运行垃圾回收器

调用 gc 方法暗示着 Java 虚拟机做了一些努力来回收未用对象失去了所有引用的对象,以便能够快速地重用这些对象当前占用的内存。当控制权从方法调用中返回时,虚拟机已经尽最大努力从所有丢弃的对象中回收了空间。

  public static void main(String[] args) {

        Date d = new Date();
        d = null;

        System.gc();
        // 在调用这句gc方法时,上面已经失去了d引用的new Date()被回收

    }
Copy after login

实际上我们并不一定需要调用gc()方法,让编译器自己去做好了。如果调用gc方法,会在对象被回收之前调用finalize()方法,但是我们也知道finalize()方法不一定会被调用。总之java在这回收方面做的远不如c和c++。我们可以规避有关回收方面的问题。当需要了解的时候最好专门的去看JVM回收机制的文章。

exit——退出虚拟机

exit(int)方法终止当前正在运行的 Java 虚拟机,参数解释为状态码。根据惯例,非 0 的状态码表示异常终止。 而且,该方法永远不会正常返回。 这是唯一一个能够退出程序并不执行finally的情况。

  public static void main(String[] args) {

        try {
            System.out.println("this is try");
            System.exit(0);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            System.out.println("this is finally");
        }

    }
Copy after login

这段程序最后只会输出 this is try 这一句话,而不会输出 this is finally 。退出虚拟机会直接杀死整个程序,已经不是从代码的层面来终止程序了,所以finally不会执行。

深度剖析System类源代码

看完了表面的方法,我们来继续学习一下System的源代码。还是老样子,找个jdk包打开rt.jar找到java.lang.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.
     */
    private static native void registerNatives();
    static {
        registerNatives();
    }
Copy after login

native不用看了,本机方法。这是可以猜得到的,因为System类要使用输入和输出流可能会用到和操作系统相关的一些本机方法。那么在static块中调用了registerNatives()方法,这个方法是本地方法我们看不到具体实现。但是注释说了:“VM will invoke the initializeSystemClass method to complete the initialization for this class separated from clinit”。

那么JVM调用的initializeSystemClass方法是怎么实现的呢?

    private static void initializeSystemClass() {

        props = new Properties();
        initProperties(props); 

        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")));

        loadLibrary("zip");

        Terminator.setup();

        sun.misc.VM.initializeOSEnvironment();

        Thread current = Thread.currentThread();
        current.getThreadGroup().add(current);

        setJavaLangAccess();
        sun.misc.VM.booted();
    }
Copy after login

这个方法就在System类中,但是我们刚才没有介绍,因为是private的方法,只是用来自己做注册使用。我整理了一下源代码去掉了无用的部分。这个方法的大概意思是说:1.初始化Properties 2.初始化输入、输出、错误流 3.进行一大堆配置。

设置输入/输出/错误流

可以注意其中的几行,setIn0,setOut0,setErr0这三个方法。这三个方法是System中public方法setIn,setOut,setErr内部调用的子方法。我们用这几个方法来设置这三个流。

    public static void setIn(InputStream in) {
        checkIO();
        setIn0(in);
    }
Copy after login

比如这是setIn方法,我们使用这个方法来设置输入流(此方法被使用的频率不是很高)。checkIO是检查IO流是否正确,setIn0是native方法,做真正的输入流替换工作。

    private static native void setIn0(InputStream in);
Copy after login

The above is the detailed content of In-depth analysis of java-System system class. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!
KeyDescription of related values
InstallationDirectory
class.version
when loading the library
Default temporary file path
To The name of the JIT compiler to use
The path to one or more extension directories
The name of the operating system
Operating system version
.separatorFile separator ( In UNIX systems it is "/")
Path separator (in UNIX systems it is ":")
Line separator ("/n" on UNIX systems)
user Account name
User’s home directory
user Current working directory