[英]What does this undefined method/collection do in this static initializer?
[英]What does this single static method do?
我不確定這是做什么的,我之前從未見過它,也找不到任何有關它的信息。
private static String[] names = { "A.ttf" };
private static Map<String, Font> cache = new ConcurrentHashMap<String, Font>(names.length);
static {
for (String name : names) {
cache.put(name, getFont(name));
}
}
塊由{\\\\some code}
。 放置的static
關鍵字表示它是一個static
塊。 static
塊稱為“ Static Initializers
,非靜態塊稱為“ Instance Initializers
。
它們都不能包含return語句。
每次創建新實例時,都會調用 non-static
塊,並且在構造函數之前將調用/執行該non-static
塊。 static
塊將僅被調用/執行一次,這將是您第一次訪問該類。
例:
class A {
static{ // static
System.out.println("Static block of Class A");
}
{ // non-static
System.out.println("Non-Static block of a instance of Class A");
}
public A(){
System.out.println("Constructing object of type A");
}
}
public class StaticTest {
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
}
}
輸出:
static block of Class A
Non-Static block of a instance of Class A
Constructing object of type A
Non-Static block of a instance of Class A
Constructing object of type A
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.