您的位置:首页 > 其它

System class 源码解读

2015-05-27 22:11 387 查看
Provides access to system-related information and resources including standard input and output.

System类提供对与系统相关的信息和资源的访问,包含一个标准的输入流和输出流。

Enables clients to dynamically load native libraries.

使客户(开发者)能够动态地加载本地函数库。

All methods of this class are accessed in a static way and the class itself can not be instantiated.

System类的所有方法和属性都是静态的,类本身不能被实例化。

静态块初始化静态成员

static {
err = new PrintStream(new FileOutputStream(FileDescriptor.err));
out = new PrintStream(new FileOutputStream(FileDescriptor.out));
in = new FileInputStream(FileDescriptor.in);
// 获取系统的行分隔符,此方法最终会调用initSystemProperties()方法初始化systemProperties属性

lineSeparator = System.getProperty("line.separator");
}

exit退出程序

/**
* 使虚拟机停止运行,并退出程序;
* 此方法在退出程序前会先执行回收垃圾处理;
* 传入的code值如果不为零,则系统显示异常终止。
*/
public static void exit(int code) {
 Runtime.getRuntime().exit(code);
 }



gc回收垃圾

/**
* 调用此方法可指示(提示)虚拟机运行垃圾收集器回收无用内存。
* 此方法仅起到提示作用,不保证垃圾收集器会运行。
* 此方法最终通过Runtime Object调用native gc()。
* 不建议手动调用gc进行垃圾回收,进行垃圾回收是一个比较耗时、消耗性能的动作,建议由系统自行调用。
*/
 public static void gc() {
     Runtime.getRuntime().gc();
 }




获取指定环境变量的值

/*
* 指定一个环境变量的名称返回环境变量的值,且不执行安全检查。
*/
private static native String getEnvByName(String name);


获取所有可用环境变量

/**
* 获取所有可用环境变量,以key-value形式返回一个map Object,且这个map不可变。
*/
public static Map<String, String> getenv() {
Map<String, String> map = new HashMap<String, String>();
for (String entry : Libcore.os.environ()) {
int index = entry.indexOf('=');
if (index != -1) {
map.put(entry.substring(0, index), entry.substring(index + 1));
}
}
// SystemEnvironment类为System内部类,其构造方法调用Collections.unmodifiableMap(Map<? extends K, ? extends V> map)方法使map不可变
return new SystemEnvironment(map);
 }




获取系统属性对象

/**
* 返回系统属性对象的引用,对此返回值进行修改,将直接作用于整个系统。
*/
public static Properties getProperties() {
if (systemProperties == null) {
initSystemProperties();
}
return systemProperties;
}


动态加载文件

/**
* 通过指定的路径标识(完整路径或者名称),动态加载或链接库。
* 与loadLibrary类似
 */
public static void load(String pathName) {
Runtime.getRuntime().load(pathName, VMStack.getCallingClassLoader());
}


传达一个终结执行对象的意图给虚拟机,但不会立即结束

/**
* 为虚拟机提供一个试图终结执行对象的提示意图,但尚未执行finalize()方法(即程序仍可正常运行)
*/
public static void runFinalization() {
Runtime.getRuntime().runFinalization();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  source code