search
HomeJavajavaTutorialIn-depth analysis of java-System system class

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;
//标准错误流

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 
    }

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(这是我的目录,每个人都不同)
    }

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

gc——运行垃圾回收器

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

  public static void main(String[] args) {

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

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

    }

实际上我们并不一定需要调用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");
        }

    }

这段程序最后只会输出 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();
    }

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();
    }

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

设置输入/输出/错误流

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

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

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

    private static native void setIn0(InputStream in);
Key Description 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

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
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
Java文档解读:System类的currentTimeMillis()方法用法解析Java文档解读:System类的currentTimeMillis()方法用法解析Nov 03, 2023 am 09:30 AM

Java文档解读:System类的currentTimeMillis()方法用法解析,需要具体代码示例在Java编程中,System类是一个非常重要的类,其封装了与系统相关的一些属性和操作。其中,currentTimeMillis方法是System类中非常常用的一个方法,本文将对该方法做详细解读并提供代码示例。一.currentTimeMillis方法概述

Win10蓝屏错误:系统服务异常Win10蓝屏错误:系统服务异常Dec 29, 2023 pm 04:04 PM

win10系统是一款非常好用的高智能系统,强大的兼容性可以确保系统在正常的使用过程中基本不会出现任何的问题,但是随着人们对win10系统的不断使用有时候系统也会出现win10开机蓝屏终止代码systemserviceexception的问题,今天小编就为大家带来了win10开机蓝屏终止代码systemserviceexception的解决办法有需要的话就快来下载吧。win10systemserviceexception蓝屏的解决办法:方法一:1、使用Windows键+R打开运行,输入“contr

电脑的system是什么电脑的system是什么Feb 22, 2023 am 10:25 AM

电脑的system是比较常见的一种系统进程,在查看进程的时候经常会看到system,这个进程简单来说就是电脑系统的意思;但是,如果电脑中出现了system.exe的进程,需要及时删除,这是一个木马病毒生成的文件,真正的system后边是没有exe后缀的。

微软宣布 System Center 2022 全面上市微软宣布 System Center 2022 全面上市Apr 14, 2023 am 09:40 AM

微软已宣布System Center 2022 的可用性。最新版本带来了 System Center Operations Manager (SCOM)、Virtual Machine Manager (VMM)、System Center Orchestrator (SCORCH)、Service Manager (SM) 和 Data Protection Manager

windows7英文版系统下载windows7英文版系统下载Jul 15, 2023 pm 07:45 PM

相信网友们都对windows7系统非常熟悉,那大家听说过windows7英文版系统吗?相信有非常多的网友都对windows7英文版系统略有耳闻,不过有的朋友找windows7英文版系统下载,今天小编就要把win7英文原版系统介绍分享给大家,让网友们都能了解到英文win7原版系统。下面就是告诉你windows7英文版系统哪里下载。win7英文原版系统已发布到MSDN订阅下载,官方首先发布的英文集成版,Windows7WithSP1,即集成SP1的Windows7光盘镜像。包含适用于多语言的SP1独

今天如何在浏览器中运行 MacOS 7 和 MacOS 8今天如何在浏览器中运行 MacOS 7 和 MacOS 8Apr 18, 2023 am 11:04 AM

时光倒流回到1990年代的Macintosh,在浏览器窗口中运行System7和MacOS8的完整虚拟安装。1990年代Mac软件的新虚拟版本存在一个缺陷,那就是它们以2020年代Mac的速度运行。您看到的是MacSE/30或Quadra700,但一切都与AppleSilicon一样快。您可以在这些模拟操作系统中进行实际工作,它们甚至可以将文档或文件从macOSMonterey拖入和拖出。但无论是出于某些实际目的还是更可能是为了纯粹的乐趣,这里是如何

如何使用Java中的Object类和System类?如何使用Java中的Object类和System类?Apr 23, 2023 pm 11:28 PM

Object是java所有类的基类,是整个类继承结构的顶端,也是最抽象的一个类。大家天天都在使用toString()、equals()、hashCode()、waite()、notify()、getClass()等方法,或许都没有意识到是Object的方法,也没有去看Object还有哪些方法以及思考为什么这些方法要放到Object中。一、JavaObject类简介-所有类的超类Object是Java类库中的一个特殊类,也是所有类的父类。也就是说,Java允许把任何类型的对象赋给Object类型的

java System类和Arrays类怎么使用java System类和Arrays类怎么使用May 22, 2023 pm 08:52 PM

一.介绍System作为系统类,在JDK的java.lang包中,可见它也是一种java的核心语言特性。System类的构造器由private修饰,不允许被实例化。因此,类中的方法也都是static修饰的静态方法。JAVA中的Arrays类是一个实现对数组操作的工具类,包括了各种各样的静态方法,可以实现数组的排序和查找、数组的比较和对数组增加元素,数组的复制和将数组转换成字符串等功能。这些方法都有对所有基本类型的重载方法。二.知识点详解1、概念在API中System类介绍的比较简单,我们给出定义

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools