My understanding of static blocks of code in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.