System中代表程序所在系统,提供了对应的一些系统属性信息,和系统操作。
System类不能手动创建对象,因为构造方法被private修饰,阻止外界创建对象。System类中的都是static方法,类名访问即可。在JDK中,有许多这样的类。

常见应用场景:

1. 获取系统当前Epoch时间:System.currentTimeMillis()

  1. //打印程序执行时间
  2. public void runningTime(){
  3. long start = System.currentTimeMillis();//当前Epoch时间x
  4. for(int i = 0 ; i < 10000; i++){
  5. System.out.println(i);
  6. }
  7. long end = System.currentTimeMillis();//当前Epoch时间y
  8. System.out.println(end - start);//当前时间y-当前时间x
  9. }

2. 终止程序,退出JVM:System.exit(int exitcode)

3. 垃圾回收:System.gc()

  1. public class Person {
  2. public void finalize(){
  3. System.out.println("垃圾收取了");
  4. }
  5. }
  6. /*
  7. * JVM在内存中,收取对象的垃圾
  8. * 当没有更多引用指向该对象时,会自动调用垃圾回收机制回收堆中的对象
  9. * 同时调用回收对象所属类的finalize方法()
  10. * static void gc()
  11. */
  12. public static void gcTest(){
  13. new Person();
  14. new Person();
  15. new Person();
  16. new Person();
  17. new Person();
  18. new Person();
  19. new Person();
  20. new Person();
  21. System.gc();
  22. }

4. 获取JVM的环境变量:System.getProperty()

一般我们用它去看如下属性:

  • os.name 操作系统
  • java.class.path Java的classpath
  • java.library.path 加载library时搜素的路径列表
  • user.name 程序当前执行用户
  • user.home 用户的家目录
  • user.dir 用户当前的工作目录

    1. String username = System.getProperty("user.name"); //henryli
    2. String userhome = System.getProperty("user.home"); //Users/henryli
    3. String userdir = System.getProperty("user.dir"); //Users/henryli/Documents/GitHub/JavaBasicPractice
    4. String osname = System.getProperty("os.name"); //Mac OS X

    5. 获取操作系统 Environment Variables

  • public static String getenv(String name):获得指定环境变量的值

  • public static Map<String, String> getenv():获得所有环境变量的map

    1. String path = System.getenv("PATH");
    2. System.out.println(path);
    3. Map<String,String> envMap = System.getenv();
    4. System.out.println(envMap);

    6. 复制数组:arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

    1. public static void copyArray(){
    2. int[] src = {11,22,33,44,55,66};
    3. int[] desc = {77,88,99,0};
    4. System.arraycopy(src, 1, desc, 1, 2);//将src数组的1位置开始(包含1位置)的两个元素,拷贝到desc的1,2位置上
    5. System.out.println(Arrays.toString(desc));
    6. }