簡體   English   中英

靜態塊和在類中分配靜態之間的區別?

[英]Difference between static block and assigning static in class?

以下兩個靜態變量初始化之間是否有任何區別:

class Class1 {    
    private static Var var;

    static {
        var = getSingletonVar();
    }  
}

class Class2 {
    private static var = getSingletonVar;
}

這兩種不同的初始化靜態變量的方法在功能上是否相同?

是的,它的功能相同。

來自Java doc

There is an alternative to static blocks — you can write a private static method:

class Whatever {
    public static varType myVar = initializeClassVariable();

    private static varType initializeClassVariable() {

        // initialization code goes here
    }
}

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

結果將是相同的。

在這兩種情況下,靜態變量將使用類加載進行初始化。

靜態方法和靜態類塊是兩回事。 需要調用靜態方法,因為靜態類塊會自動通過類加載執行。

首先你沒有在這里聲明靜態方法。 可能如果你想知道執行的順序

1) constructors

在創建實例時調用,完全獨立於#2何時發生,或者甚至根本不發生

2)static methods

調用它們時調用,完全獨立於#1何時發生,或者甚至根本不發生

3)static blocks

在初始化類時調用,這可能發生在#1或#2之前。

靜態初始化器和靜態塊都在初始化類時運行。 存在靜態塊是因為有時您希望在初始化時執行某些操作,而這些操作無法表征為簡單的賦值:

static final Logger log = Logger.getLogger(ThisClass.class);
static final String PROPS_FILE = "/some/file.properties";
static final Properties gProps;
static {
    gProps = new Properties();
    try {
        FileReader reader = new FileReader(PROPS_FILE);
        try {
            gProps.load(reader);
        } finally {
            reader.close();
        }
    } catch (IOException e) {
        throw new SomeException("Failed to load properties from " + PROPS_FILE, e);
    }
    log.info(ThisClass.class.getName() + " Loaded");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM