对于Java类加载过程中的顺序问题探究


以前记得static代码块貌似是Java类加载过程中优先级最高的,但是最近几天写代码发现不是这样的,因为static变量的优先级要比static代码块高得多,所以因此我犯了不少错误,下面以一个例子来说明一下一个类初始化为对象的时候的加载过程

  1. package com.bird.jdbc;  
  2.   
  3.   
  4. public class Test {  
  5.       
  6.       
  7.     private static A a = new A();  
  8.     private final static F f= new F();  
  9.     private B b = new B();  
  10.       
  11.     static{  
  12.         System.out.println("c");  
  13.     }  
  14.       
  15.     public Test(){  
  16.         System.out.println("Test");  
  17.     }  
  18.       
  19.     public static void main(String[] args){  
  20. //      Test t = new Test();   
  21.         try {  
  22.             Class.forName("com.bird.jdbc.Test");  
  23.         } catch (ClassNotFoundException e) {  
  24.             // TODO Auto-generated catch block   
  25.             e.printStackTrace();  
  26.         }  
  27.     }  
  28. }  
  29.   
  30. class A{  
  31.     public A(){  
  32.         System.out.println("A");  
  33.     }  
  34. }  
  35.   
  36. class B{  
  37.     public B(){  
  38.         System.out.println("B");  
  39.     }  
  40. }  
  41.   
  42.   
  43. class F{  
  44.     public F(){  
  45.         System.out.println("F");  
  46.     }  
  47. }  

大家可以看到,直接运行Test t = new test();这句话,运行结果为

  1. A  
  2. F  
  3. c  
  4. B  
  5. Test  

所以是先static变量,然后是static的代码块,然后才是普通变量,最后是构造函数

如果是运行Class.forName()函数的话,运行结果为

  1. A  
  2. F  
  3. c  

还是这样,先是static变量,然后才是static代码块,所以那种对于class.Forname加载类,只调用static代码块的误区要克服,因为还有一个static代码块在等着你,呵呵,我得记录下来以示警戒。

相关内容