Ekt-Class和类加载器的执行过程

演示1:
 1 class  Base{
 2     static int a=1;
 3     static {
 4         System.out.println("我是int:Base");
 5     }
 6 }
 7 class Sub extends Base{
 8     static int b=2;
 9     static {
10         System.out.println("我是int Sub");
11     }
12 }
13 public class Ekt2{
14     static {
15         System.out.println("init Ekt2");
16     }
17 
18     public static void main(String[] args) {
19         //启动类加载Base类
20         System.out.println(Base.a);
21         System.out.println("*****************");
22         //启动类,加载Base类,在加载Sub类
23         System.out.println(Sub.b);
24         //加载子类的时候,它会去查父类有没有加载,它会先去加载父类然后加载子类
25         int[] arr=new int [3];
26 
27         System.out.println(arr.getClass());
28         System.out.println(int[].class);
29 
30         int[] arr1=new int[5];
31         System.out.println(arr.getClass()==arr1.getClass());
32 
33         int[][] arr2=new int[3][2];
34         System.out.println(arr2.getClass()==int[][].class);
35     }
36 }

 

 1 演示2:
 2 class Test{
 3     static {
 4         System.out.println("我是Test静态块");
 5     }
 6 }
 7 public class Ekt3 {
 8     public static void main(String[] args) {
 9         try {
10             Class.forName("Ekt3.Test");
11             //表示在父类运行是不加载静态块
12             Class ff = Class.forName("Ekt3.Test",false,Thread.currentThread().getContextClassLoader());
13             //在创建类的对象时才会运行静态块
14             //通过类对象得到类的实例
15             Object o = ff.newInstance();
16 
17         } catch (ClassNotFoundException e) {
18             e.printStackTrace();
19         } catch (IllegalAccessException e) {
20             e.printStackTrace();
21         } catch (InstantiationException e) {
22             e.printStackTrace();
23         }
24     }
25 }

技术总结:

一个类的类对象是唯一的
已知对象的实例可以通过getClass()的到类对象
已知基本类型可以通过class的到类对象
加载子类的时候,它会去查父类有没有加载,它会先去加载父类然后加载子类



有6种情况,JVM会加载Class对象:
1.使用new关键字创建对象时

2.通过反射创建对象是

3.调用某个类的static方法时

4.调用某个类的static属性时

5.初始化某个类的子类时候

6.某个类标明为main()函数类(启动类)

 


 

 


 




 

posted @ 2020-08-20 18:40  Kc_blog  阅读(184)  评论(0编辑  收藏  举报