一个和系统环境进行交互的类.
System不允许被实例化, 而且是一个final类

一、不能实例化

private System() {}

二、成员变量

public final static InputStream in = null;  //这是“标准”输入流。
public final static PrintStream out = null;    //这是“标准”输出流。
public final static PrintStream err = null;    //这是“标准”错误输出流。private static native void setIn0(InputStream in);private static native void setOut0(PrintStream out);private static native void setErr0(PrintStream err);

定义的三个IO流,都是final修饰符,所以即使是public 也是不能重新赋值。

三、常用方法

1、关于SecurityManager

/*** The security manager for the system.*/private static volatile SecurityManager security = null;private static void checkIO() {SecurityManager sm = getSecurityManager();if (sm != null) {sm.checkPermission(new RuntimePermission("setIO"));}}public static void setSecurityManager(final SecurityManager s) {try {s.checkPackageAccess("java.lang");} catch (Exception e) {// no-op}setSecurityManager0(s);}private static synchronized void setSecurityManager0(final SecurityManager s) {SecurityManager sm = getSecurityManager();if (sm != null) {// ask the currently installed security manager if we// can replace it.sm.checkPermission(new RuntimePermission("setSecurityManager"));}if ((s != null) && (s.getClass().getClassLoader() != null)) {// New security manager class is not on bootstrap classpath.// Cause policy to get initialized before we install the new// security manager, in order to prevent infinite loops when// trying to initialize the policy (which usually involves// accessing some security and/or system properties, which in turn// calls the installed security manager's checkPermission method// which will loop infinitely if there is a non-system class// (in this case: the new security manager class) on the stack).AccessController.doPrivileged(new PrivilegedAction<Object>() {public Object run() {s.getClass().getProtectionDomain().implies(SecurityConstants.ALL_PERMISSION);return null;}});}security = s;}/*** Gets the system security interface.** @return if a security manager has already been established for the current*         application, then that security manager is returned; otherwise,*         <code>null</code> is returned.* @see #setSecurityManager*/public static SecurityManager getSecurityManager() {return security;}

System类定义了安全管理器,并且【volatile】修饰该变量。在初始化IO流时,需要使用安全器校验权限。

2、关于console

控制台定义console

private static volatile Console cons = null;/*** Returns the unique {@link java.io.Console Console} object associated* with the current Java virtual machine, if any.** @return  The system console, if any, otherwise <tt>null</tt>.** @since   1.6*/public static Console console() {if (cons == null) {synchronized (System.class) {cons = sun.misc.SharedSecrets.getJavaIOAccess().console();}}return cons;}

System中的console是通过【sun.misc.SharedSecrets】类获取得到的。关于SharedSecrets类这里只能简单说是关于jvm的

3、currentTimeMillis和nanoTime

获取系统时间方法

/*** 获取毫秒级的时间戳(1970年1月1日0时起的毫秒数)*/
public static native long currentTimeMillis();
/*** 获取纳秒,返回的可能是任意时间(主要用于衡量时间段)*/
public static native long nanoTime();

4、arraycopy方法

该复制为浅复制,即对象数组,只复制对象引用。

public static native void arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);

5、identityHashCode 方法

返回对象地址方法

public static native int identityHashCode(Object x);

6、加载动态库library

@CallerSensitivepublic static void load(String filename) {Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);}/***/@CallerSensitivepublic static void loadLibrary(String libname) {Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);}/*** Maps a library name into a platform-specific string representing* a native library.** @param      libname the name of the library.* @return     a platform-dependent native library name.* @exception  NullPointerException if <code>libname</code> is*             <code>null</code>* @see        java.lang.System#loadLibrary(java.lang.String)* @see        java.lang.ClassLoader#findLibrary(java.lang.String)* @since      1.2*/public static native String mapLibraryName(String libname);

7、初始化Java class

/*** Create PrintStream for stdout/err based on encoding.*/private static PrintStream newPrintStream(FileOutputStream fos, String enc) {if (enc != null) {try {return new PrintStream(new BufferedOutputStream(fos, 128), true, enc);} catch (UnsupportedEncodingException uee) {}}return new PrintStream(new BufferedOutputStream(fos, 128), true);}/*** Initialize the system class.  Called after thread initialization.*/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// 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 secretssetJavaLangAccess();sun.misc.VM.booted();}private static void setJavaLangAccess() {// Allow privileged classes outside of java.langsun.misc.SharedSecrets.setJavaLangAccess(new sun.misc.JavaLangAccess(){public sun.reflect.ConstantPool getConstantPool(Class<?> klass) {return klass.getConstantPool();}public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) {return klass.casAnnotationType(oldType, newType);}public AnnotationType getAnnotationType(Class<?> klass) {return klass.getAnnotationType();}public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) {return klass.getDeclaredAnnotationMap();}public byte[] getRawClassAnnotations(Class<?> klass) {return klass.getRawAnnotations();}public byte[] getRawClassTypeAnnotations(Class<?> klass) {return klass.getRawTypeAnnotations();}public byte[] getRawExecutableTypeAnnotations(Executable executable) {return Class.getExecutableTypeAnnotationBytes(executable);}public <E extends Enum<E>>E[] getEnumConstantsShared(Class<E> klass) {return klass.getEnumConstantsShared();}public void blockedOn(Thread t, Interruptible b) {t.blockedOn(b);}public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) {Shutdown.add(slot, registerShutdownInProgress, hook);}public int getStackTraceDepth(Throwable t) {return t.getStackTraceDepth();}public StackTraceElement getStackTraceElement(Throwable t, int i) {return t.getStackTraceElement(i);}public String newStringUnsafe(char[] chars) {return new String(chars, true);}public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) {return new Thread(target, acc);}public void invokeFinalize(Object o) throws Throwable {o.finalize();}});}

四、拓展

1、java 能否自己写一个类叫 java.lang.System

一般情况下是不可以的,但是可以通过特殊的处理来达到目的,这个特殊的处理就是自己写个类加载器来加载自己写的这个java.lang.System

JDK源码解析之 java.lang.System相关推荐

  1. JDK源码解析之 java.lang.Thread

    位于java.lang包下的Thread类是非常重要的线程类,它实现了Runnable接口,今天我们来学习一下Thread类,在学习Thread类之前,先介绍与线程相关知识:线程的几种状态.上下文切换 ...

  2. JDK源码解析之 java.lang.Integer

    teger 基本数据类型int 的包装类 Integer 类型的对象包含一个 int 类型的字段 一.类定义 public final class Integer extends Number imp ...

  3. JDK源码解析之 Java.lang.Object

    Object类是Java中其他所有类的祖先,没有Object类Java面向对象无从谈起.作为其他所有类的基类,Object具有哪些属性和行为,是Java语言设计背后的思维体现. Object类位于ja ...

  4. JDK源码解析之 Java.lang.Compiler

    Compiler类提供支持Java到本机代码编译器和相关服务.在设计上,它作为一个占位符在JIT编译器实现. 一.源码部分 public final class Compiler {private C ...

  5. JDK源码解析之 java.lang.Exception

    异常.是所有异常的基类,用于标识一般的程序运行问题.这些问题通常描述一些会被应用程序捕获的反常情况. 一.源码部分 //继承了java.lang.Throwable public class Exce ...

  6. JDK源码解析之 java.lang.Error

    java.lang.Error 错误.是所有错误的基类,用于标识严重的程序运行问题.这些问题通常描述一些不应被应用程序捕获的反常情况. 一.源码部分 //继承了java.lang.Throwable ...

  7. JDK源码解析之 Java.lang.String

    String 类代表字符串.Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现. 字符串是常量:它们的值在创建之后不能更改.字符串缓冲区支持可变的字符串.因 ...

  8. JDK源码解析之 Java.lang.Package

    如果我们在Class对象上调用getPackage方法,就可以得到描述该类所在包的Package对象(Package类是在java.lang中定义的).我们也可以用包名通过调用静态方法getPacka ...

  9. JDK源码解析之 java.lang.Class

    Java程序在运行时,Java运行时系统一直对所有的对象进行所谓的运行时类型标识. 这项信息纪录了每个对象所属的类.虚拟机通常使用运行时类型信息选准正确方法去执行,用来保存这些类型信息的类是Class ...

最新文章

  1. html外链式css运行不出来div,html+css外链式
  2. 2013\National _C_C++_A\5.网络寻路
  3. [UWP]针对UWP程序多语言支持的总结,含RTL
  4. java enumerator_NSEnumerator使用
  5. geoTools学习笔记001---(简介)
  6. 【Android 界面效果43】Android LayoutInflater的inflate方法中attachToRoot的作用
  7. android Camera相关问题及NV12剪裁旋转
  8. keil交通灯c语言,用Keilc软件设计一个交通灯程序C程序
  9. mkvtoolnix视频转换 v51.0.0中文版
  10. 2020-12-24
  11. java LPT1_com1/lpt1/prn/nul 木马后门处理方法集合
  12. dynamics crm 常用js
  13. 腾讯云主机Ubuntu之服务器环境搭建以及宝塔面板安装
  14. VUE项目学习(四):编写个人页面和配置路由
  15. 微信如何设置延迟到账 | 微信到账时间设置在哪里设置 | 微信转账后24小时/2小时/立即到账怎么设置
  16. python提示IndentationError: unexpected indent错误
  17. MOOC《基础和声》笔记
  18. GPS从入门到放弃(六) --- 开普勒轨道参数
  19. Mysql统计近30天的数据,无数据的填充0
  20. 工业设备刀具检测常用特征值提取方法及决策方法

热门文章

  1. os是android5.0,Funtouch OS 2.1曝光 完美改Android5.0
  2. C++中提高程序运行效率的方法集合
  3. qt中combox怎么使其下拉菜单的长度变长
  4. BugkuCTF-MISC题神秘的文件
  5. emlog_toolkit.php,emlog 4.0版本IIS6下伪静态划定规矩
  6. mysql 字符串类型 分区_MySQL分区类型
  7. java中strictfp么意思_什么时候应该在java中使用“strictfp”关键字?
  8. 计算机应用全能,全能计算助手
  9. linux关闭自检测进程,CentOS下自动发邮件检测某进程是否存在
  10. linux libusb应用实例,在Linux中使用libusb-1.0作为非root用户访问USB设备