Demo1.funx ();
String s=demo1.string;
Static blocks of code are called when new is a class object
or call the static method of the class when the static member variable is called
In summary, a static block of code is called when the class loader loads the class into memory, either way
Static member variables static code blocks are always initialized once, regardless of the new number of objects
Initialization sequence static member---Static code block--variable, initialization block--constructor, when class is loaded
Because static code blocks are always loaded once, the attribute
Often used to load initialization operations such as configuration files (Singleton mode)
Example
static {Configuration CFG = new Configuration ();//Cfg.configure ();//???????????????? Hibernate.cfg.xml?? Cfg.configure ("Hibernate.cfg.xml"); // ?????? Lambda?????????? Sessionfactory = Cfg.buildsessionfactory ();//Cfg.addresource ("Cn/itcast/a_helloworld/user.hbm.xml");// Cfg.addclass (User.class); // ? User????????? Canвt??????? User??????. Hbm.xml????? // ????? Sessionfactorysessionfactory = new Configuration ()//.configure ()//.buildsessionfactory ();}
Load Driver
private static Properties props = null;static{try {//Get property configured and initialize load stream to prop InputStream inputstream= JdbcUtils.class.getClassLoader (). getResourceAsStream ("Dbconfig.properties");p rops=new properties ();p rops.load ( InputStream);} catch (IOException e) {throw new RuntimeException ();} try {//Load driver class Class.forName (Props.getproperty ("Driverclassname")),} catch (ClassNotFoundException e) {throw new RuntimeException ();}}
My understanding of static blocks of code in Java