gpt4 book ai didi

java - 变量声明后的这个静态 block 是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:31:16 26 4
gpt4 key购买 nike

我以前从未见过这个 - 它叫什么?这是一个类级变量,位于文件的开头。

为了清楚起见,我指的是变量后的 static {}

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);
}

最佳答案

这是一个静态初始化 block 。它可以在类内的任何地方(但在方法外)声明,但按照惯例,它通常写在被初始化的静态变量之后。它在 Java 语言规范中指定,section §8.7 .

顾名思义,它通常用于在类加载时初始化类中静态属性的状态。来自Java tutorial :

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword (...) A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

关于java - 变量声明后的这个静态 block 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10707734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com