[英]Initialize a final variable before constructor in Java
這個問題在Java中的構造函數之前擴展了Initialize final變量,因為我對那里提供的答案不滿意。
我也有同樣的問題。 我有一些需要設置為final
變量,但是我不能這樣做,因為我需要將它們設置為需要捕獲異常的值,因此除非我將其放入構造函數中,否則就不可能實現。 這樣做的問題是,我每次想引用final
static
變量時都必須創建該對象的新實例,而這實際上沒有任何意義。
一個示例,其中每次在不同類中引用該對象時,除非創建new
實例,否則無法在構造函數內部或構造函數內部定義path
:
public class Configuration {
private static final String path;
public Configuration() throws IOException, URISyntaxException {
propertiesUtility = new PropertiesUtility();
path = propertiesUtility.readProperty("path");
}
}
您仍然可以使用靜態初始化程序,但是需要一些修飾來存儲異常,您應在以后的階段(例如在構造函數中)使用該異常。
private static final String path;
private static final java.lang.Exception e_on_startup;
static {
java.lang.Exception local_e = null;
String local_path = null;
try {
// This is your old Configuration() method
propertiesUtility = new PropertiesUtility();
local_path = propertiesUtility.readProperty("path");
} catch (IOException | URISyntaxException e){
local_e = e;
}
path = local_path; /*You can only set this once as it's final*/
e_on_startup = local_e; /*you can only set this once as it's final*/
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.