Java中static修饰一段代码实现加载时运行的用法


  1. package com.min.test;   
  2. class AA{   
  3.        
  4.     // 加载时运行,与instance无关   
  5.     static{   
  6.         System.out.println("static block ");   
  7.     }   
  8.        
  9.     AA() {   
  10.         System.out.println("AA()");   
  11.     }   
  12. }   
  13. public class JavaTest {   
  14.     /**  
  15.      * @param args  
  16.      */  
  17.     public static void main(String[] args) {   
  18.         // TODO Auto-generated method stub   
  19.            
  20.         try {   
  21.             Class.forName("com.min.test.AA");   
  22.         } catch (ClassNotFoundException e) {   
  23.             // TODO Auto-generated catch block   
  24.             e.printStackTrace();   
  25.         }   
  26.            
  27. //      AA a = new AA();   
  28.     }   
  29. }  

输出结果:

static block

加上AA a = new AA();后,输出:

static block
AA()

相关内容