Java – using static init blocks
•
Java
I know how static init blocks work
Solution
When you want to initialize one or more static variables in one place
It is useful because you can apply exception handling, which is impossible for online initialization
For example:
public static ImageIcon defaultIcon = ImageIO.read(..);
Can initialize
public static ImageIcon defaultIcon; static { try { defaultIcon = ImageIO.read(..); } catch (IOException ex){ System.out.println("No default icon available"); } }
Another application is complex initialization. For example, if a project needs multiple lines of code to initialize Suppose you have a configuration:
public static Configuration configuration; static { confuguration = new Configuration(); configuration.setSomething(..); configuration.setSomethingElse(..); ... }
The third use is to initialize some external API infrastructure An example of my current project:
static { org.apache.xml.security.Init.init(); }
However, as mykola golubyev said, static initialization blocks make code difficult to read, so use them with caution Static methods do the same thing more transparently
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码