work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

JVM 主动类和被动类的使用

Posted on 2019-06-07 20:40  work hard work smart  阅读(445)  评论(0编辑  收藏  举报

主动使用和被动使用Demo

1、创建工程一个Gradle工程

下一步

下一步

点击完成

 

2、创建类

public class MyTest1 {


    public static void main(String[] args) {
        System.out.println(MyChild1.str);
    }
}


class MyParent1{
    public static String str = "hello world";

    static {
        System.out.println("MyParent1 static block");
    }
}

class MyChild1 extends  MyParent1{
    static {
        System.out.println("MyChild static block");
    }
}

  输出结果:

MyParent1 static block
hello world

  会发现MyChild1的类静态块没有执行。

  总结:对于静态字段来说,只有直接定义了该字段的类才会被初始化。

 

 修改后的类:

public class MyTest1 {


    public static void main(String[] args) {
        System.out.println(MyChild1.str2);
    }
}


class MyParent1{
    public static String str = "hello world";

    static {
        System.out.println("MyParent1 static block");
    }
}

class MyChild1 extends  MyParent1{

    public static String str2 = "hello world 2";

    static {
        System.out.println("MyChild static block");
    }
}

  执行结果

MyParent1 static block
MyChild static block
hello world 2

 因为使用到了MyChild的类,它会被初始化。当一个类在初始化时,要求其父类全部都已经初始化完毕。最终打印结果如上面所示。 

 

3、上面1中,MyChild1没有被实例化,那MyChild类是否有被加载?

-XX:+TraceClassLoading, 用于追踪类的加载信息并打印出来
配置如下:

完整的代码

public class MyTest1 {


    public static void main(String[] args) {
        System.out.println(MyChild1.str);
    }
}


class MyParent1{
    public static String str = "hello world";

    static {
        System.out.println("MyParent1 static block");
    }
}

class MyChild1 extends  MyParent1{

    public static String str2 = "hello world 2";

    static {
        System.out.println("MyChild static block");
    }
}

  

 

打印的结果

说明MyChild类也会被加载, 最先加载的是MyTest1类

 

JVM参数

-XX:+<option>, 表示开启option选项

-XX:+<option> 表示关闭options选项
-XX:<option>=<value>, 表示将option选项的值设置为value

 

 4、首次主动使用例子

public class MyTest4 {

    public static void main(String[] args) {
        MyParent4 myParent4 = new MyParent4();
        System.out.println("-------------");
        MyParent4 myParent5 = new MyParent4();
    }
}

class MyParent4{

    static {
        System.out.println("MyParent4 static block");
    }

  打印结果:

MyParent4 static block
-------------

  说明在创建MyParent4 对象的时候,会初始化MyParent4, 但是第二次创建MyParent4的时候,就不会初始化MyParent4。所有只在主动首次使用才会初始化。