1 Star 0 Fork 165

ElonChung / Java-Review

forked from flatfish / Java-Review 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
Java-常用类-System.md 11.88 KB
一键复制 编辑 原始数据 按行查看 历史
icanci 提交于 2020-09-07 23:09 . :fire:更新文件夹

Java - 常用类 - System

从源码开始分析

public final class System {

    private static native void registerNatives();
    static {
        registerNatives();
    }

    // 私有构造器
    private System() {
    }

    // 输入流
    public final static InputStream in = null;

    // 输出流
    public final static PrintStream out = null;

    // 输出流
    public final static PrintStream err = null;

    // 系统的安全管理器
    private static volatile SecurityManager security = null;

    // 重新分配“标准”输入流。
    public static void setIn(InputStream in) {
        checkIO();
        setIn0(in);
    }

    // 重新分配“标准”输出流
    public static void setOut(PrintStream out) {
        checkIO();
        setOut0(out);
    }

    //  重新分配“标准”输出流
    public static void setErr(PrintStream err) {
        checkIO();
        setErr0(err);
    }

    private static volatile Console cons = null;
    public static Console console() {
        if (cons == null) {
            synchronized (System.class) {
                cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
            }
        }
        return cons;
    }

    // 管道流
    public static Channel inheritedChannel() throws IOException {
        return SelectorProvider.provider().inheritedChannel();
    }

    // 安全管理 IO
    private static void checkIO() {
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new RuntimePermission("setIO"));
        }
    }

    // 本地方法
    private static native void setIn0(InputStream in);
    private static native void setOut0(PrintStream out);
    private static native void setErr0(PrintStream err);

    // 设置安全管理器
    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) {
            sm.checkPermission(new RuntimePermission
                               ("setSecurityManager"));
        }

        if ((s != null) && (s.getClass().getClassLoader() != null)) {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    s.getClass().getProtectionDomain().implies
                        (SecurityConstants.ALL_PERMISSION);
                    return null;
                }
            });
        }

        security = s;
    }

    // 获取安全管理器
    public static SecurityManager getSecurityManager() {
        return security;
    }

    // 本地方法 获取从 1970年1月1日0点0分0秒 到当前之间的毫秒数
    public static native long currentTimeMillis();

    // 本地方法 获取从 1970年1月1日0点0分0秒 到当前之间的纳秒数
    public static native long nanoTime();

    // 本地方法 ,执行数组的拷贝 
    // 第一个参数 需要拷贝的数组,
    // 第二个参数 需要拷贝的数组的开始下标
    // 第三个参数 需要拷贝到的数组
    // 第四个参数 需要拷贝到的数组的开始下标
    // 第五个参数 需要拷贝的个数
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);
    // 返回给定对象相同的哈希码会被默认的方法hashCode()方法返回
    // 给定对象的与否类重写hashCode() 为空引用的哈希码是零。
    public static native int identityHashCode(Object x);

    // Properties对象
    private static Properties props;

    // 初始化 Properties 对象
    private static native Properties initProperties(Properties props);

    // 获取Properties对象
    public static Properties getProperties() {
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPropertiesAccess();
        }
        return props;
    }
    // 分隔器
    public static String lineSeparator() {
        return lineSeparator;
    }
    private static String lineSeparator;

    // 设置外部传入的 Properties 对象
    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;
    }

    // 通过key或者当前对象的 Properties 对象的key
    public static String getProperty(String key) {
        checkKey(key);
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPropertyAccess(key);
        }

        return props.getProperty(key);
    }

    // 根据 k v 获取
    public static String getProperty(String key, String def) {
        checkKey(key);
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPropertyAccess(key);
        }

        return props.getProperty(key, def);
    }

    // 设置 k v
    public static String setProperty(String key, String value) {
        checkKey(key);
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new PropertyPermission(key,
                                                      SecurityConstants.PROPERTY_WRITE_ACTION));
        }

        return (String) props.setProperty(key, value);
    }

    // 删除 某个key
    public static String clearProperty(String key) {
        checkKey(key);
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new PropertyPermission(key, "write"));
        }

        return (String) props.remove(key);
    }

    // 辅助方法
    private static void checkKey(String key) {
        if (key == null) {
            throw new NullPointerException("key can't be null");
        }
        if (key.equals("")) {
            throw new IllegalArgumentException("key can't be empty");
        }
    }

    // 获得指定的环境变量的值。 环境变量是一个依赖于系统的外部命名的值
    public static String getenv(String name) {
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new RuntimePermission("getenv."+name));
        }

        return ProcessEnvironment.getenv(name);
    }

    //  获得指定的环境变量的键值对Map对象
    public static java.util.Map<String,String> getenv() {
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new RuntimePermission("getenv.*"));
        }

        return ProcessEnvironment.getenv();
    }

    // 退出程序的方法
    public static void exit(int status) {
        Runtime.getRuntime().exit(status);
    }

    //  调用gc方法,但是JVM不一定立即执行GC
    public static void gc() {
        Runtime.getRuntime().gc();
    }

    //  运行挂起终止的任何对象的终止方法。
    public static void runFinalization() {
        Runtime.getRuntime().runFinalization();
    }

    //  终止方法 已经过时
    public static void runFinalizersOnExit(boolean value) {
        Runtime.runFinalizersOnExit(value);
    }

    // 加载一个文件
    public static void load(String filename) {
        Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);
    }

    // 加载类包
    public static void loadLibrary(String libname) {
        Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
    }

    // 调用本地方法 根据类包获取名字 win10 下是 包的dll文件
    public static native String mapLibraryName(String libname);

    // 获取一个打印流
    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);
    }

    // System类的初始化
    private static void initializeSystemClass() {
        props = new Properties();
        initProperties(props);  // initialized by the VM
        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();
    }
    
    // 
    private static void setJavaLangAccess() {
        // Allow privileged classes outside of java.lang
        sun.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();
            }
        });
    }
}

总结

  • 在面试中我们会遇到一些题目 比如:System.out.println(); 的原理,因为System类里面封装了PrintStream类、InputStream类等
  • 同样的,在System类中也封装了 Runtime类、Properties类的对象
1
https://gitee.com/elonchung/Java-Review.git
git@gitee.com:elonchung/Java-Review.git
elonchung
Java-Review
Java-Review
master

搜索帮助