java中靜態代碼塊之我的理解

來源:互聯網
上載者:User

標籤:div   resource   hbm.xml   drive   載入驅動   etc   use   .class   source   

Demo1.funx();
String s=Demo1.string;
//靜態代碼塊 會在new一個該類對象時調用

或者調用該類的靜態方法,靜態成員變數時調用

總之在類載入器將該類載入到記憶體中時 (無論是通過哪種方式) 都會調用靜態代碼塊

//靜態成員變數 靜態代碼塊永遠只被初始化一次 無論new多少個對象
//載入類時 初始化順序   靜態成員->靜態代碼塊 ->變數,初始化塊->建構函式


//由於靜態代碼塊永遠只被載入一次的特性
//常被用來載入設定檔 等初始化操作(單例模式)

 

例子

static {Configuration cfg = new Configuration();// cfg.configure(); // ????????????????hibernate.cfg.xml??// // cfg.configure("hibernate.cfg.xml"); // ??????λ??????????// sessionFactory = cfg.buildSessionFactory();// cfg.addResource("cn/itcast/a_helloworld/User.hbm.xml");// cfg.addClass(User.class); // ?User?????????в???????User??????.hbm.xml?????// ?????SessionFactorysessionFactory = new Configuration()//.configure()//.buildSessionFactory();}

  載入驅動

private static Properties props = null;static{try {//擷取Property配置 並初始化 載入流到prop中InputStream inputStream=JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");props=new Properties();props.load(inputStream);} catch (IOException e) {throw new RuntimeException();}try {//載入驅動類Class.forName(props.getProperty("driverClassName"));} catch (ClassNotFoundException e) {throw new RuntimeException();}}

  

java中靜態代碼塊之我的理解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.