可以通过编译,这样做的好处是可以在系统加载该类的时候初始化一些操作。为避免被实例化多个对象,singleton中也有类似的用法(在系统加载类后初始化该类唯一的对象)。

解决方案 »

  1.   

    是不是说 
    private static  Connection conn;
    static  Connection getConnection()  {           try {
              
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
                  conn = DriverManager.getConnection(url1, user1, password1);
                
            }
            catch (Exception e) {
                         
            }
      那是不是说  static Connection con=xxx.getConnection()  得到的con 和conn占用同一内存地址, con.close也就等于做了conn.close;
      

  2.   

    那我再問上面的星星一個問題,以下兩段代碼有何區別:-------------代碼A-------------------public class WebConst
    {
      static
     { public static ApplicationContext AC=new FileSystemXmlApplicationContext("Hibernate-Context.xml");
      
     }
    }-------------代碼B-------------------public class WebConst
    {
      public static ApplicationContext AC=new FileSystemXmlApplicationContext("Hibernate-Context.xml");
    }看來這個問題只有星星才會:)
      

  3.   

    差别就是1 上面的是静态程序块 下面的是静态变量
    2 上面的你写的错误的public static不能要,块作用域范围外不能访问
      下面的可以从类外面访问
    3 他们都在类加载的时候实例化了FileSystemXmlApplicationContext类。