在学习中遇到这样一段代码,它是在一个函数内部的,我只想知道他是在什么时候运行的为什么要给这段代码加上static?
static
{
    try
   {      
      Configuration config = new Configuration();
      config.addClass(Customer.class);
      sessionFactory = config.buildSessionFactory();
   }
   catch(Exception e)
  {e.printStackTrace();}
}

解决方案 »

  1.   

    这段代码出现在"一个函数内部"? 不可能吧? static块不能出现在函数内部的, 只是类定义的内部, 函数定义以外.static{}就是静态代码块, 块里面的代码都是在类加载的时候执行的, 所以只会执行一次.考查下面的代码:public class Foo {
      static int m = 0;
      int n = 0;  static {
        m++;
        System.out.println("the value of m now is: " + m);
      }  void increaseN() {
        n++;
        System.out.println("the value of n now is: " + n);
      }  public static void main(String[] args) {    Foo f = new Foo();    f.increaseN();
        f.increaseN();
        f.increaseN();    Foo f1 = new Foo();
        Foo f2 = new Foo();  }}n每次执行increaseN()方法后都会增加1. 而m只在第一次创建类Foo的实例时增加一次, 因为增加m的代码是static的, 只执行一次, 以后再创建更多的Foo的实例都不会执行了.