Java靜態程式碼塊載入驅動程式碼例項
阿新 • • 發佈:2020-07-15
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���ļ� // ��ʼ��SessionFactory sessionFactory = 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(); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。