Java靜態(tài)代碼塊加載驅(qū)動(dòng)代碼實(shí)例
Demo1.funx();String s=Demo1.string;
靜態(tài)代碼塊 會(huì)在new一個(gè)該類對(duì)象時(shí)調(diào)用
或者調(diào)用該類的靜態(tài)方法,靜態(tài)成員變量時(shí)調(diào)用
總之在類加載器將該類加載到內(nèi)存中時(shí) (無(wú)論是通過(guò)哪種方式) 都會(huì)調(diào)用靜態(tài)代碼塊
靜態(tài)成員變量 靜態(tài)代碼塊永遠(yuǎn)只被初始化一次 無(wú)論new多少個(gè)對(duì)象
加載類時(shí) 初始化順序 靜態(tài)成員->靜態(tài)代碼塊 ->變量,初始化塊->構(gòu)造函數(shù)
由于靜態(tài)代碼塊永遠(yuǎn)只被加載一次的特性
常被用來(lá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ū)動(dòng)
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ū)動(dòng)類 Class.forName(props.getProperty('driverClassName')); } catch (ClassNotFoundException e) { throw new RuntimeException(); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. Java 基于UDP協(xié)議實(shí)現(xiàn)消息發(fā)送3. python 如何停止一個(gè)死循環(huán)的線程4. ASP.NET MVC前臺(tái)動(dòng)態(tài)添加文本框并在后臺(tái)使用FormCollection接收值5. php5.6不能擴(kuò)展redis.so的解決方法6. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總7. 關(guān)于HTML5的img標(biāo)簽8. Python編寫nmap掃描工具9. python 爬取嗶哩嗶哩up主信息和投稿視頻10. 如何基于python3和Vue實(shí)現(xiàn)AES數(shù)據(jù)加密
