What is this static block after the variable declaration?

I had never seen this before - what is it called? This is the class level variable at the beginning of the file.

To be clear, I mean static {}after the variable.

private static final UriMatcher URI_MATCHER;
    static {
        URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
        URI_MATCHER.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH);
        URI_MATCHER.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH);
        URI_MATCHER.addURI(AUTHORITY, "books", BOOKS);
        URI_MATCHER.addURI(AUTHORITY, "books/#", BOOK_ID);
    }
+3
source share
5 answers

This is a static initialization block. It can be declared anywhere inside the class (but outside the method), but by convention it is usually written immediately after the initialization of the static variable. It is specified in the Java Language Specification, Section §8.7 .

As the name implies, it is usually used to initialize the state of static attributes in a class during class loading. From the Java tutorial :

, , {} (...) , . , , .

+4

. , , static : 1, 2, 3 . :

public class Main {
    static int[] array1 = {1, 2, 3, 4 ...};

    static int[] array2;
    static {
        array2 = new int[N];
        for (int i = 0; i < N; i++) {
            array2[i] = i;
        }
    }
}
+2

, var URI_MATCHER

+1

This is a static initialization block . It allows you to "tune" your static fields that cannot be executed correctly in class instance methods.

0
source

This is just a static initialization block. Check out: http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

0
source

All Articles