Table of Contents
Non-instantiable System class" > Non-instantiable System class
Field" > Field
Commonly used methods in System" > Commonly used methods in System
arraycopy—— ArrayCopy" >arraycopy—— ArrayCopy
currentTimeMillis——Return the number of milliseconds
attribute" >getProperty——Get the system attribute
gc——运行垃圾回收器
exit——退出虚拟机
深度剖析System类源代码" > 深度剖析System类源代码
初始化
设置输入/输出/错误流
Home Java javaTutorial In-depth analysis of java-System system class

In-depth analysis of java-System system class

May 07, 2017 am 09:40 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java documentation interpretation: Usage analysis of the currentTimeMillis() method of the System class Java documentation interpretation: Usage analysis of the currentTimeMillis() method of the System class Nov 03, 2023 am 09:30 AM

Java document interpretation: Usage analysis of the currentTimeMillis() method of the System class, specific code examples are required. In Java programming, the System class is a very important class, which encapsulates some properties and operations related to the system. Among them, the currentTimeMillis method is a very commonly used method in the System class. This article will explain the method in detail and provide code examples. 1. Overview of currentTimeMillis method

Win10 blue screen error: System service exception Win10 blue screen error: System service exception Dec 29, 2023 pm 04:04 PM

The win10 system is a very easy-to-use and highly intelligent system. Its strong compatibility can ensure that the system will basically not have any problems during normal use. However, as people continue to use the win10 system, sometimes the system will also have problems. The problem of Win10 booting blue screen termination code SystemServiceException. Today I will bring you the solution to Win10 booting Blue Screen termination code SystemServiceException. If you need it, please download it quickly. Solution to win10systemserviceexception blue screen: Method 1: 1. Use Windows key + R to open Run and enter “contr

What is the computer system? What is the computer system? Feb 22, 2023 am 10:25 AM

The computer system is a relatively common system process. You will often see system when viewing the process. This process simply means the computer system; however, if the system.exe process appears on the computer, it needs to be deleted in time. , this is a file generated by a Trojan horse virus. There is no exe suffix behind the real system.

How to use Object class and System class in Java? How to use Object class and System class in Java? Apr 23, 2023 pm 11:28 PM

Object is the base class of all Java classes, the top of the entire class inheritance structure, and the most abstract class. Everyone uses toString(), equals(), hashCode(), wait(), notify(), getClass() and other methods every day. Maybe they don’t realize that they are methods of Object, and they don’t look at what other methods Object has. And think about why these methods should be placed in Object. 1. Introduction to JavaObject class - the super class of all classes Object is a special class in the Java class library and is also the parent class of all classes. In other words, Java allows any type of object to be assigned to the Object type

windows7 english version system download windows7 english version system download Jul 15, 2023 pm 07:45 PM

I believe that netizens are very familiar with the Windows 7 system. Have you heard of the Windows 7 English version system? I believe that many netizens have heard about the Windows 7 English version system. However, some friends are looking for the Windows 7 English version system to download. Today I will The editor is going to share the introduction of the original version of win7 in English with everyone, so that netizens can understand the original version of win7 in English. The following is to tell you where to download the English version of Windows 7 system. The original English system of win7 has been released to MSDN for subscription download. The official English integrated version was first released, Windows7WithSP1, which is the Windows7 CD image with integrated SP1. Includes SP1 standalone for multiple languages

Microsoft announces general availability of System Center 2022 Microsoft announces general availability of System Center 2022 Apr 14, 2023 am 09:40 AM

Microsoft has announced the availability of System Center 2022. The latest version brings System Center Operations Manager (SCOM), Virtual Machine Manager (VMM), System Center Orchestrator (SCORCH), Service Manager (SM) and Data Protection Manager

How to run MacOS 7 and MacOS 8 in your browser today How to run MacOS 7 and MacOS 8 in your browser today Apr 18, 2023 am 11:04 AM

Step back in time to the Macintosh of the 1990s and run complete virtual installations of System 7 and MacOS 8 in a browser window. One flaw with new virtual versions of 1990s Mac software is that they run at the speed of a 2020s Mac. You're looking at a MacSE/30 or Quadra700, but everything is as fast as Apple Silicon. You can actually work in these simulated operating systems, and they can even drag documents or files in and out of macOS Monterey. But whether for some practical purposes or more likely just for pure fun, here's how

How to use java System class and Arrays class How to use java System class and Arrays class May 22, 2023 pm 08:52 PM

1. Introduction to System as a system class. In the java.lang package of JDK, it can be seen that it is also a core language feature of Java. 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 methods modified by static. The Arrays class in JAVA is a tool class that implements array operations. It includes a variety of static methods that can implement array sorting and search, array comparison, adding elements to arrays, array copying, and converting arrays into String functions. These methods have overloaded methods for all basic types. 2. Detailed explanation of knowledge points 1. The concept is relatively simple introduced in the System class in the API. We give the definition.

See all articles
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