What does Static {} mean in the Java Syntax?

后端 未结 7 1248
野趣味
野趣味 2020-12-13 13:49

I came across this Java code:

static {
    String aux = \"value\";
    try {
        // some code here
    } catch (Exception e) { }
    String UUID_prefix =         


        
7条回答
  •  执笔经年
    2020-12-13 14:12

    This is a static initialization block. Think of it like a static version of the constructor. Constructors are run when the class is instantiated; static initialization blocks get run when the class gets loaded.

    You can use them for something like this (obviously fabricated code):

    private static int myInt;
    
    static {
        MyResource myResource = new MyResource();
        myInt = myResource.getIntegerValue();
        myResource.close();
    }
    

    See the "Static Initialization Blocks" section of Oracle's tutorial on initializing fields.

提交回复
热议问题