这样的结构叫 static块 ,一般是一个类初始化时运行的代码。 注意,是类的初始化,不是对象的初始化。
也就是你在定义对象是,它运行的初始化代码,并且只有第一次定义时才运行。之后就不再运行初始化了。
一个类中可以可以有很多static块。static块按顺序执行。
import org.hibernate.cfg.*;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
这个时候,就能明白,当然,是前提有用到这个的