Java靜態(tài)代碼塊加載驅(qū)動代碼實例
Demo1.funx();String s=Demo1.string;
靜態(tài)代碼塊 會在new一個該類對象時調(diào)用
或者調(diào)用該類的靜態(tài)方法,靜態(tài)成員變量時調(diào)用
總之在類加載器將該類加載到內(nèi)存中時 (無論是通過哪種方式) 都會調(diào)用靜態(tài)代碼塊
靜態(tài)成員變量 靜態(tài)代碼塊永遠只被初始化一次 無論new多少個對象
加載類時 初始化順序 靜態(tài)成員->靜態(tài)代碼塊 ->變量,初始化塊->構(gòu)造函數(shù)
由于靜態(tài)代碼塊永遠只被加載一次的特性
常被用來加載配置文件 等初始化操作(單例模式)
例子
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���ļ� // ��ʼ��SessionFactory sessionFactory = new Configuration()// .configure()// .buildSessionFactory(); }
加載驅(qū)動
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 { //加載驅(qū)動類 Class.forName(props.getProperty('driverClassName')); } catch (ClassNotFoundException e) { throw new RuntimeException(); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. css進階學(xué)習(xí) 選擇符2. python實現(xiàn)自動化辦公郵件合并功能3. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以內(nèi))4. python爬蟲beautifulsoup解析html方法5. python web框架的總結(jié)6. 以PHP代碼為實例詳解RabbitMQ消息隊列中間件的6種模式7. 解決python logging遇到的坑 日志重復(fù)打印問題8. html小技巧之td,div標簽里內(nèi)容不換行9. Python基礎(chǔ)之numpy庫的使用10. 詳解Python模塊化編程與裝飾器
