I have come across some Java code that I don't know how to interpret.
The part that I have marked I do not know what it is, it does not reach me with the knowledge that I have.
Any reference so I can look it up?
Code:
package hibernate1;
import org. hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SessionFactoryUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration()
.configure()
.buildSessionFactory();
} catch ( Throwable ex ) {
System.err.println(
"Err iniciando SessionFactory: " + ex
);
throw new ExceptionlnlnitializerError( ex );
}
} // static
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
I don't understand the structure. Declare the property sessionFactory
, and then there's a block static
, I don't know what that is.
The following structure:
... is called a static initialization block (roughly translating from English: static initialization block ).
In a way, it acts like a class constructor, but instead of initializing the instance members of a class, rather, the static initialization block allows you to initialize the static members of the class, which you can't do with constructors. normal.
The static initialization block executes only once for a given class, no matter how many instances you create. And you are guaranteed to execute before any instance constructors.
In your example, the static initialization block is used to initialize the static variable
sessionFactory
. The block is executed only once for the classSessionFactoryUtil
before you have a chance to use it.You can find more basic information about this structure in the official Oracle tutorial: Static Initialization Blocks .
If you want more complete, but more technical information, you can find it directly in the Java language specification: