java中静态代码块之我的理解

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();
	}	
}

  

原文地址:https://www.cnblogs.com/lt123/p/7215317.html